Showing posts with label JSON. Show all posts
Showing posts with label JSON. Show all posts

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;
   }