JSON vs. JavaScript objects

JSON's syntax comes from JavaScript object literals, so the two look alike. A JavaScript object is a value inside a running program, written with the full language. JSON is a text format with a small, fixed grammar. Any JSON text is also a valid JavaScript expression, but a lot of JavaScript isn't valid JSON.

A JavaScript object literal, not JSON
{
  name: 'Ada Lovelace', // a comment
  born: 1815,
  tags: ['math', 'poetry',],
}

Open this example in j2n

The differences

JavaScriptJSON
KeysQuotes are optional: {name: 1}Always in double quotes: {"name": 1}
StringsSingle, double or backtick quotesDouble quotes only
Last itemA trailing comma is allowedNo trailing comma
Comments// and /* */None
ValuesAnything, including functions, undefined, NaN and datesObjects, arrays, strings, numbers, true, false and null
NumbersAlso 0xFF, 1_000 and BigInt 10nDecimal only, like 255 or 2.5e3

Converting between them

JSON.stringify(value) turns a JavaScript value into JSON text, and JSON.parse(text) reads JSON text back into a value. Some values don't survive the trip:

To turn a JavaScript object literal you copied from code into JSON, quote every key, switch to double quotes, and remove comments and trailing commas.