JavaScript JSON Grammar: Data, Not Code
Quick answer
JSON is a text format for exchanging structured data. It has a smaller grammar than JavaScript expressions and does not execute programs.
How it works
JSON values are objects, arrays, strings, numbers, true, false and null. Object member names and strings require double quotes. Comments, trailing commas, undefined, BigInt literals, functions and single-quoted strings are not JSON. A top-level primitive is valid. Whitespace outside strings is limited to space, tab, LF and CR.
console.log(JSON.parse("42"), JSON.parse("null"));Expected output in Node.js:
42 nullTop-level primitive values are allowed.
try { JSON.parse('{"x":1,}'); } catch(e) { console.log(e.name); }Expected output in Node.js:
SyntaxErrorA trailing comma is invalid in JSON.
Common mistakes
A JavaScript object literal is not necessarily valid JSON. Do not execute data text as code.
Practice
Classify a few configuration strings as valid or invalid JSON, then fix their syntax.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
JavaScript JSON Grammar: Data, Not Code — Knowledge Check
Apply the taught concept and predict the output.
Which text is valid JSON?
Can a JSON document contain a function literal?
Which quote delimiter is required for JSON string literals?
What is the exact console output in JavaScript JSON Grammar: Data, Not Code example 1?
console.log(JSON.parse("42"), JSON.parse("null"));What is the exact console output in JavaScript JSON Grammar: Data, Not Code example 2?
try { JSON.parse('{"x":1,}'); } catch(e) { console.log(e.name); }