JSON Fundamentals

Introduction

A new data format which is built on JavaScript is called JavaScript Object Notation[JSON]. It is a lightweight data format based on JavaScript syntax. JSON definitions can be included within JavaScript files. This post speaks about basic syntax of JSON and advantages over XML.

It is important to understand the specific syntax for array and object literals before we learn JSON syntax.

Array Literals

Array literals are specified by square brackets and comma delimited list of JavaScript values.

1.gif
 
The above syntax is much equivalent to the following traditional syntax

2.gif
 
Notice that both methods of declaring arrays is acceptable when writing JavaScript, but array literals are valid in JSON.

Object Literals

Object literals are used to store name-value pairs. An Object literal is defined by two curly braces{}. You can place any number of name-value pairs, defined with a string, a colon and the value. Each name-valued pair must be followed with a comma.

3.gif
 
The same object can be created using JavaScript Object Constructor like
 
Again, Notice either approach is valid in JavaScript but only object literal notation is valid in JSON.

4.gif

JSON Syntax

JSON syntax is mixture of object and array literals to store data and only difference from above examples is that JOSN doesn't have variables.

5.gif
 
Remember JSON represents only data, it has no concept of variables,assignments.

Assuming you are having string of information in sResult and certainly not an object, to transform it into an object simply use the JavaScript eval() function.

6.gif
 
The obvious benefit of using JSON as data format is it takes the evaluation of data out of your hands and grants the faster access to the information.

The Advantages of JSON over XML can be found at http://www.techbubbles.com/aspnet/json-vs-xml/.


Similar Articles