Saturday, June 23, 2007

JSON- Javascript Object Notation

Intro
JSON stands for Javascript Object Notation. JSON is a way of writing or expressing JavaScript Objects so that it can be easily read by both the computer and humans. Unlike XML or eXtensible Mark up Language the JSON is much more compact and easier to Parse.

XML takes the form


<Tag>
<Tag2>Information</Tag2>
<Tag>


JSON takes the form

var obj = {
an_array : [element1, element2 , element3 ....],
a_property : "property",
a_multi_array : [ [,,,],[,,,],...]
};


In order to parse an XML response, we have to use the following notation,
Suppose we are returning an XML response from a server using Ajax. The common method to extract the useful information is :

var xml = xmlHttp.responseXML;
var list= xml.getElementsByTagName("TAG");

for(i=0;i < list.length;i++)
{
// loop through and extract the values
}


This can be replaced with the new JSON object notation by

var strobj = xmlHttp.responseText;
var obj = eval("("+strobj+")");
obj.an_array[0];
obj.a_multi_array[0][0];
// ....


The Notation
All object lies between the { }
each of the properties has a label and an associated value or an array.
It is specified as label : value
a , separates the label-value pairs.
Arrays are enclosed in square brackets [ ] and comma separated.

In short a JSON object looks like

var blog = {
name: "the Digital Me",
author : "arun prabhakar",
pages : ["http://url1/","http://url2/"];
complexarray: [[0,10,10],[7,5,7],[1,9,8],[7,1,4]];
};


JSON and PHP
PHP has 2 built in functions to help with the JSON format.
json_encode
json_decode

Links

json.org
php.net JSON Functions

0 comments: