JSON
What is it
Language independent, lightweight data-interchange format.
{ "first_name": "John", "age": 27, "address": { "street_address": "21 2nd Street", "city": "New York", "state": "NY", "postal_code": "10021-3100" }, "phone_numbers": [ { "type": "home", "number": "212 555-1234" }, { "type": "office", "number": "646 555-4567" } ], "spouse": null }
JSON can be built on two structures:
- Collection of
name:value
pairs- commonly referred to as an
object
,record
,struct
,dictionary
,hash table
,keyed list
, orassociative array
.
- commonly referred to as an
- Ordered list of values
- commonly known as
array
,vector
,list
, orsequence
.
- commonly known as
// array JSON.parse('[1,2,3]'); // [1,2,3] // object JSON.parse('{"1": 1,"2" :2 ,"3": 3}') // {1: 1, 2: 2, 3: 3}
JSON does not support undefined
or comments.
- JSON is not, in this sense, 1-to-1 with Javascript.
Errors
Single vs Double Quotes
JSON
object should use single quotes ''
to wrap records to avoid conflicting with key declaration.
Should be using double quotes ""
for key
representation.
Should NOT use double quotes for wrapping the JSON records
// WRONG: will throw a SyntaxError JSON.parse("{'foo': 1}");
Trailing Commas
parse
does not allow trailing commas or empty records
// trailing empty record; will throw a SyntaxError JSON.parse('[1, 2, 3, 4, ]'); // trailling comma; will throw a SyntaxError JSON.parse('{"foo" : 1, }');