Json parsing in Javascript

JSON Syntax Rules:
1)Data should be in name/value pairs
2)Data is separated by commas
3)Curly braces hold objects
4)Square brackets hold arrays

Example 1:


1
2
3
4
5
6
<script>
var json = '{"Name":"Rahul","Id":"1"}',
    obj = JSON.parse(json);

alert("Name:  "+obj.Name);
</script>


Output:













Example 2:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
<script>

var text = '{"employees":[' +
'{"firstName":"Rahul","lastName":"Ram" },' +
'{"firstName":"Raja","lastName":"Nair" },' +
'{"firstName":"Harish","lastName":"Selvaraj" }]}';

obj = JSON.parse(text);

alert("First Name:  "+obj.employees[0].firstName );
alert("First Name:  "+obj.employees[2].firstName );

</script>



Output:


No comments:

Post a Comment