JSON data is written in the format: name/value pairs.
A name/value pair consists of the field name (in double quotes), followed by a colon, and then the value.
For example :
"firstName" : "John"
JSON objects
JSON objects are written in curly braces, and objects can contain multiple name/value pairs. E.g:
{"firstName" : "John","lastName":"Doe"}
JSON arrays are written in square brackets, and arrays can contain multiple objects:
{ "employees":[{"firstName" : "John","lastName":"Doe"},{"firstName" : "Anna","lastName":"Smith"}] }
JSON uses Javascript syntax, so no additional software is required to process JSON in Javascript. An array of objects can be created and assigned by Javascript:
var employees = [{"firstName" : "John","lastName":"Doe"},{"firstName" : "Anna","lastName":"Smith"} ]The first item in an array of Javascript objects can be accessed:
employees[0].lastName
What is returned is:
Doe
Convert JSON string to Javascript object
Create a Javascript string, the string is data in JSON format,
var text = '{ "employees":['+'{"firstName" : "John","lastName":"Doe"},'+'{"firstName" : "Anna","lastName":"Smith"}] }'
Strings can be converted to Javascript objects using the Javascript built-in function JSON.parse():
var obj = JSON.parse(text);
The return value is
{ "employees":[{"firstName" : "John","lastName":"Doe"},{"firstName" : "Anna","lastName":"Smith"}] }
JSON.stringfy() is used to convert Javascript values to JSON strings