JSON syntax is derived from JavaScript object notation syntax.
- Data is in name/value pairs (
, )
- Curly braces hold objects where name is followed by :(colon)({ : })
- Data is separated by commas { : , : }
- Square brackets hold arrays and values are separated by comma (,). the values can also be an object. [ , ]
JSON vs Javascript Objects
The JSON format looks similar to JavaScript objects.
JSON vs JS Keys/ Name
JSON
The only difference is in JSON, keys must be strings, written within double quotes.
JavaScript
In JavaScript, keys can be strings, numbers, or identifier names.
JSON vs JS Values
In JSON, values must be one of the following data types.
- an object (JSON object)
- a string
- a number
- an array
- a boolean
- null
In JavaScript values can be all of the above and also other valid JavaScript expression like below.
- a function
- a date
- undefined
String Values
In JSON, string values must be written with double quotes:
JSON
In JavaScript, you can write string values with double or single quotes:
JavaScript
Accesing JSON data
Since JSON syntax is derived from JavaScript object notation you can access the json data similar way as we access javascript objects.
Below is an example to access data from the javascript object.
Example
var person = { "name":"David", "age":32, "city":"California" };
You can access a JavaScript object like this.
// returns John
person.name;
OR
// returns John
person["name"];
Modifying Data
person.name = "Gilbert";
OR
person["name"] = "Gilbert";
JavaScript vs JSON Arrays
JavaScript arrays can also be used as JSON The same way JavaScript objects can be used as JSON.