Wednesday, December 3, 2008

JSON - JavaScript Object Notation

JSON is the acronym for Javascript Object Notation. It describes elegant and simple format to represent the javascript objects and arrays as single string. It can be good intermediate format for web based applications. Usually in web based application, to take the database values to the front-end, xml is used as intermediate format. And then using javascript that particular xml is rendered. Or else directly values are rendered as HTML. This is what happens in Tibco GI also.

JSON is majorly used in all the AJAX sites as intermediate format for data transaction between the server and the browser (client).

Consider a table in JSON format (string),

var jsonstr="{
Invoice : [ { id: 1, total: 100, custId: 10 },
{ id: 2, total: 200, custId: 10 },
{ id: 3, total: 300, custId: 10 },
{ id: 4, total: 400, custId: 20 } ],
Customer : [ { id: 10, acctBalance: 1000 },
{ id: 20, acctBalance: 2000 },
{ id: 30, acctBalance: 3000 } ]
}";

In one step it can be turned as JSON object, it is nothing but a Javascript Object

var tableData = eval('('+jsonstr+')');

NOW,

tableData.Invoice gives the complete Invoice array (table)....

tableData.Invoice[0].total gives the first row total 100

Now let me explain you how JSON is organized in a simple way,

Object starts with { and ends with } and can contain one or more elements, and here the element value can be object or array or a single simple value, A element is as described here, total:100 , element is a name value pair delimited by colon. For example a object can be,

{ id: 1, total: 100, custId: 10 }

{ id: 1, total: 100, custId: 10, acl:{username:anand,passwd:se3ret}, accesscount:[10] }

Array starts with [ and ends with ] contain set of elements, the element can be of any type, it may be a object, integer, string, double. For example,

[1,'anand',1.32]

[{ id: 1, total: 100, custId: 10 }, 10, 'anand', 10.82]

JSON can be array or object. There are lot of parsers available on http://json.org, that converts the data betweeen JSON and any Higher Level Language or vice versa. In fact parser available for javascript itself, it basically converts json string to json object as we did it using eval command above.

--
Anand
anand.sadasivam@googlemail.com

No comments: