Sub topic 3
Reading JSON Text with JSON.parse
This chapter assumes you know JavaScript objects, arrays, and primitive types, and that you have seen JSON text, for example in an HTTP response or a file. It covers what JSON.parse returns and how JSON text maps onto JavaScript values. Error handling and revivers get their own chapters later.
The working model
JSON.parse(text) reads a string of JSON and builds new JavaScript values from it. It does not run the text as code. A strict parser reads it against the JSON grammar and creates plain objects, arrays, strings, numbers, booleans, and null.
const text = '{"name":"Ada","age":36,"tags":["math","code"],"admin":false,"manager":null}';
const user = JSON.parse(text);
console.log(user.name); // "Ada"
console.log(user.tags.length); // 2
console.log(Array.isArray(user.tags)); // true
console.log(user.manager); // null
console.log(Object.getPrototypeOf(user) === Object.prototype); // trueEvery call creates a fresh object graph. If you parse the same string twice, you get two separate objects that share no references, so changing one leaves the other untouched.
const source = '{"items":[1,2,3]}';
const a = JSON.parse(source);
const b = JSON.parse(source);
a.items.push(4);
console.log(b.items); // [1, 2, 3]
console.log(a === b); // falseHow JSON types map to JavaScript
| JSON value | JavaScript result |
|---|---|
| `{ ... }` | Plain object (`Object.prototype`) |
| `[ ... ]` | `Array` |
| `"text"` | `string` |
| `12`, `-3.5`, `1e3` | `number` (a 64-bit double) |
| `true` / `false` | `boolean` |
| `null` | `null` |
No JSON value produces undefined, a Date, a Map, or a class instance. A date in JSON is just a string, and it stays a string after parsing unless you convert it yourself.
const event = JSON.parse('{"at":"2024-01-15T09:30:00.000Z"}');
console.log(typeof event.at); // "string"Top-level values do not have to be objects
Any JSON value is valid at the top level, and whitespace around tokens is ignored.
console.log(JSON.parse('42')); // 42
console.log(JSON.parse('"hello"')); // "hello"
console.log(JSON.parse('true')); // true
console.log(JSON.parse('null')); // null
console.log(JSON.parse(' [1, 2]\n')); // [1, 2]A common mistake is passing an already-parsed value back into JSON.parse. The argument is converted to a string first, which gives confusing results:
const obj = { a: 1 };
// JSON.parse(obj); // SyntaxError: String(obj) is "[object Object]"
console.log(JSON.parse(null)); // null, because String(null) is "null"
// JSON.parse(undefined); // SyntaxError: "undefined" is not JSONCommon surprises
Duplicate keys do not cause an error. The last one wins:
console.log(JSON.parse('{"role":"user","role":"admin"}').role); // "admin"Strings are decoded, so escape sequences in the text become real characters:
const s = JSON.parse('"line1\\nline2 \\u00e9"');
console.log(s); // line1
// line2 éThe parser is strict. Single quotes, trailing commas, unquoted keys, comments, undefined, and NaN are all rejected with a SyntaxError. The chapter on handling invalid JSON shows how to catch that error safely.
Exercise
What does this code log, and why? const t = '{"n":1,"list":[{"x":1}],"n":2}'; const p = JSON.parse(t); const q = JSON.parse(t); p.list[0].x = 99; console.log(p.n, q.list[0].x, typeof JSON.parse('"5"'));
Show answer
It logs 2 1 "string". The duplicate key "n" resolves to its last value, 2. Each parse builds an independent object graph, so changing p.list[0].x does not affect q, which still holds 1. The text '"5"' is a JSON string, so it parses to the string "5", not a number.
Exercise
A teammate writes const data = await response.json(); const user = JSON.parse(data); and gets a SyntaxError mentioning "[object Object]". What is wrong, and how do you fix it?
Show answer
response.json() already returns the parsed object. Passing that object to JSON.parse converts it to the string "[object Object]", which is not valid JSON. Remove the JSON.parse call and use data directly, or call response.text() if you need the raw text.