Tuesday, March 23, 2010

.NET: JavaScript Object Notation (JSON)


JSON is a lightweight format for exchanging data between the client and server. It is often used in Ajax applications because of its simplicity and because its format is based on JavaScript object literals.

JSON is built on two structures:

JSON Array:

An array is an ordered collection of values. An array begins with [ (left bracket) and ends with ] (right bracket). Values are separated by , (comma).
Array literals are created with square brackets as shown below:

var Beatles = ["Paul","John","George","Ringo"];//This is the equivalent of:
var Beatles = new Array("Paul","John","George","Ringo");

JSON Object:

An object is an unordered set of name/value pairs. An object begins with { (left brace) and ends with } (right brace). Each name is followed by : (colon) and the name/value pairs are separated by , (comma).

Object literals are created with curly brackets:

var Beatles = {
           "Country" : "England",

           "YearFormed" : 1959,
           "Style" : "Rock'n'Roll"

              }

Accessing JSON Object:

alert(Beatles.Style); //Dot Notation

alert(Beatles["Style"]); //Bracket Notation

Little Complex Example of Accessing JSON Object:
var menu = {"menu":
{"id": "file",
"value": "File",

"popup": {

    "menuitem": [

      {"value": "New", "onclick": "CreateNewDoc()"},
      {"value": "Open", "onclick": "OpenDoc()"},
      {"value": "Close", "onclick": "CloseDoc()"}
                ]
          }
}
};

function json (){
   alert(menu.menu.popup.menuitem[0].value); //Return "New"
   return  false;
   }

   

1 comment:

Jayden Bell said...

This is to good, thanks for sharing your knowledge with us. Following links also helped me and develpers.

http://msdn.microsoft.com/en-us/library/bb299886.aspx

http://www.mindstick.com/Articles/af150297-b1e0-4316-958e-5a0b11a4a016/?JavaScript%20Object%20Notation%20JSON%20in%20JavaScript%20and%20Net

Post a Comment