Saturday, January 23, 2010

JSON startup

JSON - javascript object notation

To know about the JSON, first go through the following basics in js.

Array:

var arr = new Array("first", "second", "third", "fourth");

Retrieve value from array

arr[0] => "first"
arr[1] => "second"


Object:

var sample_object = {
"name1" : "value1",
"name2" : "value2",
"name3" : "value3",
"name4" : "value4"
}

sample_object.name1 => "value1"
sample_object["name1"] => "value1"



Objects in Array

var object_array = [
{
"first_element" : "first_value"
},
{
"second_element" : "second_value"
}
]
object_array[0] => returns first object
object_array[1].second_element => second object value


Arrays in Object:

var sample_object = {
"name1" : "value1",
"name4" : [1,2,3,4]
}
sample_object.name4 => [1,2,3,4]
sample_object.name4[0] => 1

var str_json = JSON.stringify(sample_object);
var js_object = JSON.parse(str_json);
JSON.parse(strJSON) - converts a JSON string into a JavaScript object.
JSON.stringify(objJSON) - converts a JavaScript object into a JSON string.