Solved

Parsing JSON response

Posted on 2009-07-09
6
1,020 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
Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

 

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

Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Requirements JQuery 1.6+ HTML CSS Introduction This article was inspired by an EE question (http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/Q_28372511.html) on how to make a page show some balloons animate up a page…
I found this questions asking how to do this in many different forums, so I will describe here how to implement a solution using PHP and AJAX. The logical flow for the problem should be: Write an event handler for the first drop down box to get …
The viewer will learn the basics of jQuery, including how to invoke it on a web page. 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.: (CODE)
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…

809 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