JSON(JavaScript Object Notation)
What is JSON?
JSON stands for JavaScript Object Notation. JSON is a lightweight data-
interchange format. JSON is "self-describing" and easy to understand. JSON is
language independent
JSON Example
This example defines an employees object: an array of 3 employee records
(objects):
{
"employees":[
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter", "lastName":"Jones"}
]
}
JSON Syntax Rules
Data is in name/value pairs. Data is separated by commas. Curly braces hold
objects. Square brackets hold arrays
JSON Arrays
JSON arrays are written inside square brackets. Just like in JavaScript, an array can
contain objects:
"employees":[
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter", "lastName":"Jones"}
]
In the example above, the object "employees" is an array. It contains three objects.
Each object is a record of a person (with a first name and a last name).
Converting a JSON Text to a JavaScript Object
A common use of JSON is to read data from a web server, and display the data in a
web page.
For simplicity, this can be demonstrated using a string as input.
First, create a JavaScript string containing JSON syntax:
var text = '{ "employees" : [' +
'{ "firstName":"John" , "lastName":"Doe" },' +
'{ "firstName":"Anna" , "lastName":"Smith" },' +
'{ "firstName":"Peter" , "lastName":"Jones" } ]}';
Then, use the JavaScript built-in function JSON.parse() to convert the string into a
JavaScript object:
var obj = JSON.parse(text);
Finally, use the new JavaScript object in your page:
Example
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML =
obj.employees[1].firstName + " " + obj.employees[1].lastName;
</script>