Introduction to JSON (JavaScript Object Notation)

Wednesday, February 18th, 2009 | Business, Tutorials | by

JSON, JavaScript Object Notation, is a very useful tool for AJAX developers (and many others I’m sure).

XML is fairly difficult for JavaScript to parse out.  It also includes quite a bit of infrastructure overhead in certain applications.  

Implementation of JSON can be very easy, it is imported natively in JavaScript through the eval() procedure.  It is also supported by many server side languages.

Lets take a basic example of an XML statement and see it’s JSON equivalent:

XML
<book id=”123″><author>Tom Jones</author></book>

JSON
{“book”: {“id”:”123″, “author”:”Tom Jones”}}

It may seem more cryptic, but if you look, that’s just because there are fewer iterations of key words.  The compression gets extended when you implement longer arrays of data.

The best part about JSON, in my opinion, is the speed increase you get when using it in javascript.  Please implement something in XML and JSON with the same data, you will notice a significant performance increase.

JSON is easy to consume in JavaScript:

objJSON = eval(jsonDataFeed);

You can access data (using our example earlier):

alert(objJSON.book.id);
alert(objJSON.book.author);

Server side implementation can be quite simple as well:

$dataObject = array();
$dataObject["book"] = array();
$dataObject["book"]["id"] = 123;
$dataObject["book"]["author"] = "Tom Jones";
echo (json_encode($dataObject));

Ask any questions in the comments below.  

Here are some articles to continue your exploration of JSON:

Related Posts

Tags: , , , , , , ,

3 Comments to Introduction to JSON (JavaScript Object Notation)

Joshua Kugler
March 2, 2009

As a rule, do NOT use eval(code) to parse your JSON data. If you ever have user provided content inside JSON encoded data, you could execute malicious javascript in that user’s browser. Taken a look at the JSON parsers at http://json.org/

seangw
March 2, 2009

Joshua is correct, you should not directly use “eval(code)” in JS as it is a high security risk. Use an existing JSON parser (jQuery for example).

If the source is absolutely secure (no user entered data, etc.) you can use “eval”, it is very fast doing this directly without parsing. Just know, that any non-trusted content makes that a high risk method.

Peter
March 5, 2009

Crockford’s JSON parser will properly parse (not eval!) the JSON string. However, at the time of writing this, jQuery still uses eval [if ( type == "json" ) data = window["eval"]("(" + data + ")");].

Leave a comment

*


Please share, it makes me happy:

Subscribe to Email Alerts

Follow Me

Follow seangw on twitter

Archives

Categories

prestashop theme

virtuemart template