HomeToolsAbout a20k

JSON

What is it

Language independent, lightweight data storing

{ "first_name": "John", "last_name": "Smith", "is_alive": true, "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" } ], "children": [ "Catherine", "Thomas", "Trevor" ], "spouse": null }

JSON.parse()

JSON.parse() method parses a JSON string, constructing the JavaScript value or object described by the string

const json = '{"result":true, "count":42}'; const obj = JSON.parse(json); console.log(obj.count); // 42 console.log(obj.result); // true

Caveats

Single vs Double Quotes

JSON object should use single quotes '' to wrap records as a string

  • should be using double quotes "" for key
  • should NOT be using double quotes for wrapping the JSON records
// WRONG: will throw a SyntaxError JSON.parse("{'foo': 1}");

parse does not allow trailing commas or empty records

// WRONG: both will throw a SyntaxError JSON.parse('[1, 2, 3, 4, ]'); JSON.parse('{"foo" : 1, }');

JSON.stringify()

Converts JS object or value to a JSON string

JSON.stringify({ x: 5, y: 6 }); // "{"x":5,"y":6}" JSON.stringify({}) // '{}' JSON.stringify(true) // 'true' JSON.stringify('foo') // '"foo"' JSON.stringify([1, 'false', false]) // '[1,"false",false]' JSON.stringify([NaN, null, Infinity]) // '[null,null,null]' JSON.stringify({ x: 5 }) // '{"x":5}' JSON.stringify(new Date(2006, 0, 2, 15, 4, 5)) // '"2006-01-02T15:04:05.000Z"'

Can stringify array of objects

JSON.stringify( [ new Number(3), new String('false'), new Boolean(false) ] ); // "[3,"false",false]"

Some data types will be forced to null when stringified

JSON.stringify( { x: [10, undefined, function(){}, Symbol('')] } ); // "{"x":[10,null,null,null]}"
© VincentVanKoh