Solved

Parsing JSON response

Posted on 2009-07-09
6
1,018 Views
Last Modified: 2013-11-08
I have an unordered list, with each list item attributed with an id that will contain a location code.  After receiving an ajax response from the server, I am provided with an array of location codes that may or may not match the ones in my unordered list; if they do, I need to add a class of "on" to each list item.

What I need is the js needed to parse the json response and then the logic to add the css class if a location code matches one in my list.

Should be trivial for a js ninja, complicated for a novice like me!
<ul>

   <li id="a7456">Location 1</li>

   <li id="a7457">Location 2</li>

   <li id="a7458">Location 3</li> 

   <li id="a7459">Location 4</li>

</ul>
 

// and if a location code matches

<li id="a7456" class="on">Location 1</li>

Open in new window

0
Comment
Question by:aznprncritic
  • 4
  • 2
6 Comments
 
LVL 20

Assisted Solution

by:ddayx10
ddayx10 earned 500 total points
ID: 24820105
May not help yo uso much if you are not using .NET, but if not you will have to get a JS class that will deserialize for you...

...either way logic for updating CSS class on unordered list items is sound.
****ASPX CODE WITH UL / CSS / and JavaScript****

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title>Managing JSON</title>

    <style type="text/css">

		.on{color:Red;}

    </style>

    <script type="text/javascript">

		

		//from body onload

		function getJArray()

		{

			jsonArray.GetJArray(rFunction); //call service to get JSON Serialized Array

		}

		

		//web service returns value which is collected here and deserialized into an array

		function rFunction(rValue)

		{

			var jArray = new Array();

			jArray = Sys.Serialization.JavaScriptSerializer.deserialize(rValue);

			addCSSClass(jArray); 

		}

		

		//check ul for li's that have same text as array, adding css class if so...

		function addCSSClass(jArr)

		{

			var ul = document.getElementById('listOfItems');

			

			for(i=0;i<ul.childNodes.length;i++)

			{

				for(j=0;j<jArr.length;j++)

				{

					//had to add this to trim(could have done diff) li innerHTML because it was coming with space.

					var chkStr = ul.childNodes[i].innerHTML.substring(0,ul.childNodes[i].innerHTML.lastIndexOf(' '));

					

					if(chkStr == jArr[j])

					{ ul.childNodes[i].className = 'on'; }

				}

			}

			

		}

    

    </script>

</head>

<body onload="getJArray();">

    <form id="form1" runat="server">
 

		<asp:ScriptManager ID="sm" runat="server">

			<Services><asp:ServiceReference Path="~/svc/jsonArray.asmx" /></Services>

		</asp:ScriptManager>

		

		<ul id="listOfItems">

			<li>item1</li>

			<li>item2</li>

			<li>itemWontGetClass</li>

			<li>item3</li>

			<li>item4</li>

			<li>item5</li>

			<li>itemWontGetClass</li>

		</ul>
 
 
 

    </form>

</body>

</html>
 
 
 

****WEBSERVICE returning serialized array****
 

Imports System.Web

Imports System.Web.Services

Imports System.Web.Services.Protocols

Imports System.Web.Script.Serialization

Imports System.Collections.Generic
 

<System.Web.Script.Services.ScriptService()> _

<WebService(Namespace:="http://tempuri.org/")> _

<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _

<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _

Public Class jsonArray

    Inherits System.Web.Services.WebService
 

    <WebMethod()> _

    Public Function GetJArray() As String
 

        Dim valueList As List(Of String) = New List(Of String)

        valueList.Add("item1")

        valueList.Add("item2")

        valueList.Add("item3")

        valueList.Add("item4")

        valueList.Add("item5")
 

        Dim json As New JavaScriptSerializer()
 

        Return json.Serialize(valueList.ToArray)

    End Function
 

End Class

Open in new window

0
 
LVL 20

Expert Comment

by:ddayx10
ID: 24820118
I guess as I think about it JavaScript can pretty well handle a JSON serialized string. You could replace the following:

Change:
jArray = Sys.Serialization.JavaScriptSerializer.deserialize(rValue);

To:
jArray = eval(rValue);
0
 
LVL 20

Expert Comment

by:ddayx10
ID: 24846636
Did you give up on this or figure it out? Is there something about my sample that does not make sense? Maybe I can provide things in a different context if I know that you still need help, and what is confusing you.
0
Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

 

Accepted Solution

by:
aznprncritic earned 0 total points
ID: 24846846
hi ddayx10,

Thanks for your proposed solution.  I actually went with this using jquery:

for (var i in json.location) {
   $('[rel=' + json.location[i] + ']').addClass('on');
}

<ul>
   <li rel="a7456">Location 1</li>
   <li rel="a7457">Location 2</li>
   <li rel="a7458">Location 3</li>
   <li rel="a7459">Location 4</li>
</ul>
0
 

Author Comment

by:aznprncritic
ID: 24846865
Used my own solution
0
 
LVL 20

Expert Comment

by:ddayx10
ID: 24855181
I think you might consider assigning some points. You did ask a question. I did give a proper and working solution. Your solution does not adhere to the criteria you laid out as to working with JSON. I stayed engaged with the thread without any feedback from you except to say a week later that you solved it yourself using different techniques.

You did find another solution, but you also solicited help, wasted or not I think it's important that you acknowledge the effort that was given. If you had engaged and decided to go another route I might have a different perspective, but in this case I don't think you should assign yourself points for this.
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Suggested Solutions

What is a Lightbox? A Lightbox is the effect you see when you click, for example, an image and the screen fades out and up pops the same image but in its full size dimensions. There are lots of Lightbox effects for jQuery. Problem is they are a…
In this article you'll learn how to use Ajax calls within your CodeIgniter application. To explain this, I'll illustrate how to implement a simple contact form to allow visitors to send you an email through your web site.
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

757 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now