Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

Parsing JSON response

Posted on 2009-07-09
6
Medium Priority
?
1,032 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 2
6 Comments
 
LVL 20

Assisted Solution

by:ddayx10
ddayx10 earned 2000 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
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

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

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

This article discusses how to implement server side field validation and display customized error messages to the client.
In this blog, we’ll look at how improvements to Percona XtraDB Cluster improved IST performance.
The viewer will learn how to dynamically set the form action using jQuery.
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)

610 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