Tuesday, October 2nd, 2007

Ajaxian Featured Tutorial: Parse JSON with jQuery and JavaScript

Category: jQuery, JSON

<p>Last week, we posted a tutorial by Brian Reindel which showed how to parse XML with jQuery. The feedback was pretty good but many readers felt that JSON is the data packet format of choice and an XML-focused tutorial wasn’t their cup of tea. Brian promised a follow-up tutorial focusing on JSON and he has delivered.

In his tutorial, Parse JSON with jQuery and JavaScript, Brian takes you step-by-step through the process of retrieving and parsing a JSON packet:

Getting JSON using jQuery is extremely straightforward. Just like $.ajax(), there is a $.getJSON() method, with a call to a file, and a function to pass the data through for parsing. The common $.each() method in jQuery can be used to traverse the “nodes” (keys) that you indicate. You could just as easily use your own for loop.

As usual, Brian includes plenty of code examples to further reinforce his techniques and provides a source code download for you to review.

You can catch both tutorials here:

jQuery and XML revisited
Parse JSON with jQuery and JavaScript

Related Content:

Posted by Rey Bango at 8:59 am
16 Comments

+++--
3.3 rating from 96 votes

16 Comments »

Comments feed TrackBack URI

Good job Brian. Love how you approached the scenarios. We are a .NET shop, just got started in JQuery. Most of the times we use JSON but there are times we get back xml directly from web services.

Both tutorials are very useful to me, very easy to read.

Comment by Liming — October 2, 2007

I’m confused. I thought one of the major advantages of JSON is that you don’t have to parse it. What ever happened to eval?

Comment by dan — October 2, 2007

@Liming – Thanks!
@dan – There has been some confusion around my use of the word “parse”. Since JSON is object literal notation, JavaScript understands the object structure, and does not need to parse it. However, in some sense, if you do not know what you want, you will need to use regular expressions to parse the JSON data. With any server-side language that wants a response in JSON, you will always still have to build a wrapper to parse the data. In the comments for the post it was pointed out that one such parser (interpreter) is called JXPath:

http://commons.apache.org/jxpath/

Comment by Brian Reindel — October 2, 2007

JXPath is for Java :)

Comment by Brian Reindel — October 2, 2007

jquery *and* javascript! Amazing that you can use these two languages together finally.

nate grover

Comment by Nate Grover — October 2, 2007

How to write “Hello World” program not using IO in at least 100 lines?

@Brian – If you do not know what you want, what on earth you gonna have in your regexps? If you DO know what you want but the structure of JSON is not fully defined then eval it first and use JS reflection. On server side you can use number of libraries for JSON parsing. JSON-RPC is probably the best one.

Comment by Robert — October 2, 2007

@Brian – What are you talking about? RegExps or whatever? As Dan says, there is no need to parse JSON. JSON is already JavaScript. You are just adding pointless noise around the term JSON. Please stop doing it.

@Ajaxian – this is a terrible post. You are not furthering the aim of Ajax at all with posts of this dubious quality.

Comment by Dean Edwards — October 2, 2007

@Dean
You have got to be joking me. First, where did I mention that JSON is not JavaScript? Second, the regular expressions are not for parsing JSON. Read the post first before you decide to comment here. An expression is used to find several values in JSON that may be three to four levels deep, possibly an array type value nested within a hash type value. You cannot grab this information without an expression. Think XPath for JSON. It is not that you do not know what you want – it is that you know you want a lot of it and there is no simple way to get it.

Comment by Brian Reindel — October 2, 2007

Brian wrote, “You cannot grab this information without an expression”.

var data = eval(resultText);
alert(data[5].foo.blah.noo[0].grog.doIt(“now”).monkey[0][0].name);

Is that expression enough to grab “values in JSON that may be three to four levels deep”? Ha, ha, ha. Your example is retarded. You might not always do this poorly, but this was a real stinker. Besides, if there is some awesome “hash type value” nested way down there then add a proper function to it to search for the “array type value”. Or by “hash type value” did you simply mean the key? Whatever, if “hash type value” is some data type then add a proper function for it to access its own complex data. You don’t need to “parse” it.

Oh, and since when is it called a “JSON packet”? Packet? Is that supposed to sound cool and low-level? Can I call my Ajax object a socket? Can I call the response text a byte stream? Ha, ha, ha. I think you’ve been getting too much byte stream from JSON’s packet in your socket. Ah, ha, ha, ha.

Comment by Roustabout — October 3, 2007

@Roustabout agree.
Really, original post looks strange. Brian says he uses jquery to query object structure (not JSON, it’s object already), but the only thing he uses is $.each() to iterate object items. With same quality and in _less code_ he can just use simple for() loop to count stuff. Not saying that his sample is lame and have bugs (values array will contain null in case isPermaLink is missing, and count will not be equal to array length. BTW what count is for anyway).

after rewriting his sample i came to this shorter and simpler version:

var res = [];
for(var i=0, t; t=json.channel.items[i]; i++) {
var p = t.guid.isPermaLink;
if (p!=undefined) res.push(p);
}
alert(res.length);

JXPath is another story, and more useful from some points.

Comment by anonymous — October 3, 2007

I’ve invented this great thing… you pull the chain which flushes the toilet which makes the rubber duckie move which flips the switch of a small electric motor which brings down a sledgehammer… on a non-existent nut :)

Comment by Jerome — October 3, 2007

THe ONLY reason this was posted is because it used jQuery and thats Rey’s pet js library. :( waste o space.

Comment by Mike — October 3, 2007

Instead of bashing the article and saying that this is just crap, how about you leave some positive feedback on how he can improve his script. Maybe you should make sure you read the whole post, download the example and come up with a better solution for the problem. I don’t think that Brian would be upset with this, more then likely he would appreciate it and update his post to have the best solution possible. I didn’t see anywhere in the post, in which he states he is the “Javascript Master”, and what he says is final.

I find it funny, Dean Edwards resorts to being immature and bashing someone who spent time to help his readers WHO asked for a JSON explanation with jQuery, because the guy did one about jQuery and XML. How do you expect us all to further our knowledge with comments like that, if you feel that put off by it being posted here, explain to Brian what he is doing wrong and how to fix it.

Blog postings are meant to be open discussions, unless you are an egomaniac and think what you say is the only solution. Most of the time people who post articles like this are open for improvements suggested in comments.

Comment by Dan Shields — October 3, 2007

This is not Brian’s blog – this is a website that usually weeds out the cruft to post relevant and useful articles. Its not a question of tweaks, improvements or fixes – much like George Bush being made president, it should never have happened in this or any other universe.

Comment by Jerome — October 3, 2007

This article spreads incorrect and bad information. That is why its soo bad. You should never do what this article suggests. NEVER.

Comment by Mike — October 3, 2007

Need more ‘using jQuery and javascript’ tutorials, owh wait I don’t.

Comment by Dom — October 3, 2007

Leave a comment

You must be logged in to post a comment.