Friday, August 3, 2007

JSON Made Simple

Hi All,

I was working with JSON format in one of the web application for sometime. Here I am sharing my experience with all of you. JSON is acronym for JavaScript Object Notation. It is simple a format presenting javascript values as array(s) or object(s).

JSON is nothing but collection javascript objects or arrays or both. The format is well described at http://json.org/. For the first sight it might look complicated, but it is very simple.

If you ask why JSON? then this could be the answer - JSON data can be easily manipulated in the Web UI using javascript. Also with AJAX (Asynchronous Javascript for XML) you can take the ability of manipulation till the Server Pages. There are lot of parser available in market, that can turn JSON data to the appropriate server side language data. You can find more parsers at http://json.org/

The other answer could be, if you want XML data that supposed to be manipulated in HTML based Web UI, the option you have is you have to parse it using javascript, it will lead to the code overhead. Otherwise you can handle it at server-side, it will make web page to refresh many times, even if you handle it with AJAX, slowliness will be there at all the time. So JSON is the best alternate. Convert XML data to JSON in server side script. Pump the json string thru' AJAX as part reponse to AJAX request to the Web UI, then you could manipulate easily with javascript. In this way your web page will look more dynamic.

Let me take you through the JSON format

-> Object starts with '{' and closed with '}'
-> Array starts with '[' and closed with ']'

Object:-
-> Object contains set of key value pairs separated by ':' and delimited by ','
example: {"name":"Anand Sadasivam","age":20 }

Array:-
-> Array contains set of values delimited by comma
example: [172,65,42,"Cricket","Chess","Foot Ball"]

Example JSON contains both array and object:
{"person":{"name":"Anand Sadasivam","age":20 },"details":[172,65,42,"Cricket","Chess","Foot Ball"]}

If you observe the above example, the first key-value pair contains object as value. Like that the second key value pair contains array as value.

So like that JSON can be nested n number of times.

'eval' statement:
eval statement can turn JSON data in string format to JSON object. For example

var data="{'person':{'name':'Anand Sadasivam','age':20 },'details':[172,65,42,'Cricket','Chess','Foot Ball']}";

var jsonData=eval('('+data+')');

In the above code data in the eval statement is parametrized by parenthesis to restrict object evaluates to value in case of single key value pair.

Hope this helps...

--
You can reach me at anand.sadasivam@googlemail.com

No comments: