Sub topic 1
What JSON Is and How It Differs from JavaScript Objects
JSON (JavaScript Object Notation) is a text format for exchanging data. It borrowed its look from JavaScript object literals, so the two are easy to confuse. They are different things. A JavaScript object is a value that lives in memory while your program runs. JSON is a string of characters that follows a strict grammar. That string can be saved to a file, sent over HTTP, or read by a program written in any language.
This chapter covers the JSON grammar: which values it allows, which characters are legal, and where it differs from the object literal syntax you write every day. Later chapters cover JSON.stringify and JSON.parse in detail. Here, JSON.parse only appears as a quick way to check whether a piece of text is valid JSON.
Prerequisites
This chapter assumes you are comfortable with:
- JavaScript objects, arrays, and primitive types (string, number, boolean,
null,undefined) - Functions and arrow functions
try/catchexception handling- The general idea of sending data as text, for example an HTTP API response body or a value saved in
localStorage
You can run every example in Node.js 18+ or a modern browser console.
JSON Is Text, Defined by a Standard
Two documents define JSON: ECMA-404 and IETF RFC 8259. They describe the same grammar. RFC 8259 adds rules for exchanging JSON between systems, such as requiring UTF-8 encoding. Neither document mentions JavaScript's runtime. JSON describes characters, not objects.
That distinction matters when you talk about your code. Developers often say "a JSON object" when they mean a plain JavaScript object. In this tutorial, "JSON" always means text:
const value = { name: "Ada" }; // a JavaScript object (in memory)
const text = '{"name":"Ada"}'; // JSON text (a string)
console.log(typeof value); // "object"
console.log(typeof text); // "string"When an API "returns JSON," your code receives a string (or bytes that decode to one). You have to parse it before you can read .name.
The Six JSON Value Types
JSON has exactly six kinds of values. Everything else in JavaScript has no direct JSON form.
| JSON type | Example | JavaScript value after parsing |
|---|---|---|
| object | `{"a": 1}` | plain `Object` |
| array | `[1, 2, 3]` | `Array` |
| string | `"hello"` | string |
| number | `-12.5e3` | number (a 64-bit double) |
| boolean | `true`, `false` | boolean |
| null | `null` | `null` |
JSON has no undefined, functions, symbols, BigInt, Date, Map, Set, NaN, Infinity, or class instances. The next chapters show what JSON.stringify does when it meets them. For now, remember that JSON's type system is much smaller than JavaScript's.
The grammar is recursive. Objects and arrays contain values, and those values can be objects and arrays again.
A JSON document can have any value at its top level. Under RFC 8259, 42, "hi", and null are each complete, valid JSON texts. Some older tools only accepted an object or array at the top level, but JSON.parse accepts any value.
The Syntax Rules, Precisely
Objects and keys
- Keys must be strings in double quotes.
{"a": 1}is valid.{a: 1}and{'a': 1}are not. - Members are separated by commas, with no comma after the last one.
- The colon between key and value is required, and whitespace around it is optional.
Strings
- Strings use double quotes only. JSON has no single-quoted strings and no template literals.
- A string may not contain a raw control character (U+0000 to U+001F). That means a literal newline or tab inside a string is invalid. Write it as an escape sequence instead.
- The only allowed escapes are
\",\\,\/,\b,\f,\n,\r,\t, and\uXXXXwith exactly four hex digits. JavaScript escapes such as\x41,\',\0, and\u{1F600}are invalid in JSON. - Characters outside the Basic Multilingual Plane, such as most emoji, can appear directly or as a surrogate pair like
"\uD83D\uDE00".
Numbers
JSON numbers are stricter than JavaScript numeric literals:
- An optional leading minus sign is allowed. A leading
+is not. - No leading zeros:
0,0.5, and10are fine, but007is invalid. - A decimal point must have digits on both sides:
.5and5.are invalid. - Exponents are allowed:
1e3,1E+2,2.5e-4. - No hex (
0x1F), octal (0o7), binary (0b1), or numeric separators (1_000). - No
NaN,Infinity, or-Infinity.
The grammar itself sets no limit on number size or precision. JavaScript parses every JSON number into a double, which is where precision problems come from. A later chapter covers this.
Literals and whitespace
true,false, andnullmust be lowercase.True,NULL, andundefinedare invalid.- Whitespace between tokens can only be space, tab, line feed, or carriage return. A non-breaking space (U+00A0) or a byte order mark causes a parse error in
JSON.parse.
Things JSON simply does not have
- Comments, either
//or/* */ - Trailing commas in objects or arrays
- Computed keys, shorthand properties, methods, getters, and spread syntax
- Variables or expressions of any kind.
{"total": 1 + 2}is invalid.
JavaScript Literal Versus JSON: Side by Side
| Feature | JavaScript object literal | JSON |
|---|---|---|
| Unquoted keys | `{ a: 1 }` allowed | Not allowed |
| Single-quoted strings | `'x'` allowed | Not allowed |
| Trailing commas | Allowed | Not allowed |
| Comments | Allowed | Not allowed |
| `undefined`, functions | Allowed as values | No such values |
| `NaN`, `Infinity` | Allowed | Not allowed |
| Hex numbers, `1_000` | Allowed | Not allowed |
| Leading `+`, `.5`, `5.` | Allowed | Not allowed |
| Expressions like `1 + 2` | Evaluated | Not allowed |
| Duplicate keys | Last one wins | Spec says keys "SHOULD" be unique; `JSON.parse` keeps the last |
| `__proto__` key | Sets the prototype | Becomes an ordinary own property |
Every valid JSON text is also a valid JavaScript expression. Since ES2019, this includes strings that contain the characters U+2028 and U+2029, which earlier JavaScript versions rejected. The reverse is not true: most object literals you write are not valid JSON.
Checking Validity in Practice
The quickest way to test a candidate string is to give it to JSON.parse and see whether it throws. The chapter on parse errors builds a proper helper for this. This script only labels each input:
const candidates = [
'{"name": "Ada", "age": 36}',
'{name: "Ada"}',
"{'name': 'Ada'}",
'{"tags": ["a", "b",]}',
'{"n": 007}',
'{"n": .5}',
'{"n": NaN}',
'{"a": 1} // comment',
'{"text": "line1\nline2"}',
'{"text": "line1\\nline2"}',
'"just a string"',
'42',
'null',
' \t\n -0 ',
];
for (const text of candidates) {
let verdict;
try {
JSON.parse(text);
verdict = "valid";
} catch {
verdict = "invalid";
}
console.log(verdict.padEnd(8), JSON.stringify(text));
}Output:
valid "{\"name\": \"Ada\", \"age\": 36}"
invalid "{name: \"Ada\"}"
invalid "{'name': 'Ada'}"
invalid "{\"tags\": [\"a\", \"b\",]}"
invalid "{\"n\": 007}"
invalid "{\"n\": .5}"
invalid "{\"n\": NaN}"
invalid "{\"a\": 1} // comment"
invalid "{\"text\": \"line1\nline2\"}"
valid "{\"text\": \"line1\\nline2\"}"
valid "\"just a string\""
valid "42"
valid "null"
valid " \t\n -0 "The two line1/line2 inputs need a closer look, because two layers of escaping are involved. In the first one, the JavaScript string literal "\n" puts a real newline character into the JSON text, and raw control characters are forbidden inside JSON strings. In the second one, "\\n" puts a backslash followed by n into the text. That is the JSON escape for a newline, so the input is valid. This difference catches people out when they write JSON inside JavaScript source code by hand.
Two Subtle Differences Worth Knowing
Duplicate keys
RFC 8259 says object names SHOULD be unique but does not require it. Parsers differ in how they handle duplicates. JSON.parse keeps the last value:
const parsed = JSON.parse('{"role": "user", "role": "admin"}');
console.log(parsed.role); // "admin"This can turn into a security problem when two systems parse the same text differently. For example, a validator might read the first role while the application reads the last one. The chapter on untrusted input covers this.
The `__proto__` key
In an object literal, __proto__: value sets the object's prototype. JSON.parse creates an ordinary own property with that name instead:
const literal = { "__proto__": { greet: "hi" } };
console.log(Object.keys(literal)); // []
console.log(literal.greet); // "hi" (inherited from the prototype)
const parsed = JSON.parse('{"__proto__": {"greet": "hi"}}');
console.log(Object.keys(parsed)); // [ '__proto__' ]
console.log(parsed.greet); // undefinedSo the same characters can mean different things depending on which grammar reads them. The danger comes later, if your code merges a parsed object into another object without care. That is the root of prototype pollution bugs.
Common Mistakes
- Calling an in-memory object "JSON." Being precise makes it obvious when a value needs parsing or stringifying.
- Hand-editing JSON config files like JavaScript. A trailing comma or a
//comment breaks the file. Formats such as JSON5 and JSONC (used for VS Code's settings) allow these, butJSON.parsedoes not. - Double-encoding. If you call
JSON.stringifyon a string that is already JSON text, you get a quoted, escaped string such as"{\"a\":1}". Parsing that once gives back a string, not an object. - Assuming non-JSON values survive.
NaN,undefined, andDatehave no JSON form. Expect them to change or disappear when serialized.
Exercise
Which of these are valid JSON texts? (a) {"a": [1, 2, 3]} (b) {"a": 0x10} (c) [true, null, "x"] (d) {"a": 1,} (e) "\u00e9" (f) -1.5E-3 (g) {"a": 'b'}
Show answer
Valid: (a), (c), (e), (f). Invalid: (b), because JSON has no hex numbers; (d), because trailing commas are not allowed; (g), because strings must use double quotes. A bare string like (e) and a bare number like (f) are complete JSON texts at the top level.
Exercise
Rewrite this JavaScript literal as valid JSON text, keeping as much information as JSON can represent: { id: 1_000, label: 'Café', ratio: .25, tags: ['x',], missing: undefined, score: NaN }
Show answer
One correct answer is {"id": 1000, "label": "Café", "ratio": 0.25, "tags": ["x"], "score": null}. The keys gain double quotes, the numeric separator and the bare .25 are rewritten, and the trailing comma goes. undefined has no JSON form, so missing is dropped. NaN cannot be represented, so null is the usual stand-in, and it is what JSON.stringify would produce.
Exercise
A JavaScript file contains const t = '{"msg": "a\tb"}'; JSON.parse(t); and it throws. Explain why, and give two ways to fix it.
Show answer
Inside the single-quoted JavaScript string, \t becomes a real tab character, so the JSON text contains a raw control character inside a string, which JSON forbids. Fix 1: escape the backslash so the JSON text contains the two characters \t, as in '{"msg": "a\\tb"}'. Fix 2: build the value as an object and generate the text, as in JSON.stringify({ msg: "a\tb" }), which escapes the tab for you.