19 September, 2010

JSON Basics

JSON is just Javascript. It is a wat to represent objects in Javascript. Using JSON does not involve working with Document Object Model (DOM). Below is a simple JSON format:
var jsnData = { "totals": [
{"location" : "First", "itemsSold" : 10, "bought": 40},
{location": "Second", "itemsSold" : 120, "bought" : 60},
{"location" : "Third", "itemsSold" : 20, "bought" : 40}
]};
Now the above JSON data can be accessed as follows:
//Get total items sold for first location
var firstItemsSold = jsnData.totals[0].itemsSold,
Similarly,
var secondItemsSold = jsnData.totals[1].itemsSold;
var secondItemsSold = jsnData.totals[1].bought;

Accessing the json based server response as json format
//lets consider basic example
//code for xmlhttprequest
if(xhr.status == 200) {
var jsnData = eval( '(' + xhr.responseText + ')' );
alert(jsnData.totals[0].itemsSold);
}
JSON is a better way to send objects or arrays to a server. And for working with such data, server should use some JSON library.

No comments: