Sub topic 3
Reading JSON Text with JSON.parse
JSON.stringify turns values into text. JSON.parse turns that text back into JavaScript values. This chapter covers how parsing works, what values you get back, and the details that tend to surprise developers. Examples include JSON that arrives from an HTTP API, top-level primitives, duplicate keys, and text that has been encoded twice.
This chapter assumes you know JavaScript objects, arrays, and primitive types, and that you have read the earlier chapters on JSON syntax and JSON.stringify. Error handling, revivers, large-number precision, and untrusted input each get a chapter of their own later. Here they appear only where they affect the basic model.
The Basic Contract
JSON.parse(text) reads a string that must be valid JSON and returns the JavaScript value it describes. That value can be an object, an array, a string, a number, a boolean, or null.
const text = '{"name":"Ada","age":36,"tags":["math","code"],"active":true,"manager":null}';
const user = JSON.parse(text);
console.log(user.name); // "Ada"
console.log(user.tags.length); // 2
console.log(typeof user.age); // "number"
console.log(user.manager); // null
console.log(Array.isArray(user.tags)); // trueEach call builds a completely new structure. If you parse the same text twice, you get two separate objects that happen to have equal contents.
const text = '{"items":[1,2,3]}';
const a = JSON.parse(text);
const b = JSON.parse(text);
console.log(a === b); // false
console.log(a.items === b.items); // false
a.items.push(4);
console.log(b.items); // [1, 2, 3]This independence is why some developers use a stringify-then-parse round trip to copy data. A later chapter explains when that works and when it breaks.
How JSON Types Map to JavaScript Values
JSON has six kinds of value, and each one maps to a single JavaScript type. Parsing never produces undefined, functions, symbols, Date objects, Maps, or class instances.
| JSON value | Example text | JavaScript result |
|---|---|---|
| object | `{"a":1}` | Plain object whose prototype is `Object.prototype` |
| array | `[1,2]` | Ordinary `Array` |
| string | `"hi"` | Primitive string |
| number | `3.5`, `-2e3` | Primitive number (a 64-bit double) |
| boolean | `true` | `true` or `false` |
| null | `null` | `null` |
Two results from this mapping cause bugs often.
The first is that dates come back as strings. If a server sends "2024-01-15T09:30:00.000Z", you get a string, not a Date. Calling .getFullYear() on it throws a TypeError. The reviver chapter shows how to turn those strings back into dates while parsing.
The second is that class identity is lost. JSON text has no record of which class created an object, so parsing gives you plain objects with no methods.
class Point {
constructor(x, y) { this.x = x; this.y = y; }
length() { return Math.hypot(this.x, this.y); }
}
const text = JSON.stringify(new Point(3, 4)); // '{"x":3,"y":4}'
const parsed = JSON.parse(text);
console.log(parsed instanceof Point); // false
console.log(typeof parsed.length); // "undefined"
const restored = new Point(parsed.x, parsed.y);
console.log(restored.length()); // 5Top-Level Values Do Not Have to Be Objects
Modern JSON (RFC 8259) allows any value at the top level, not only an object or an array. JSON.parse accepts all of them.
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]Whitespace before and after the value is ignored. Inside the text, whitespace may only appear between tokens. Note that JSON.parse("null") returns null. If your code checks the result with a truthiness test such as if (!result), it cannot tell valid null JSON apart from 0, false, or "".
The Argument Is Converted to a String First
JSON.parse first converts its argument to a string with String() and then parses that string. This conversion causes some odd results when the argument is not a string at all:
console.log(JSON.parse(null)); // null (String(null) is "null")
console.log(JSON.parse(123)); // 123 (String(123) is "123")
console.log(JSON.parse(true)); // true
try {
JSON.parse(undefined); // String(undefined) is "undefined"
} catch (err) {
console.log(err.name); // "SyntaxError"
}
try {
JSON.parse({ a: 1 }); // String({a:1}) is "[object Object]"
} catch (err) {
console.log(err.name); // "SyntaxError"
}The last case appears in real code. Someone calls JSON.parse on a value that some library has already parsed. The object becomes "[object Object]", and the error message mentions an unexpected character o at position 1. When you see that message, check whether the value was already an object.
Strict Syntax: What Parse Rejects
JSON.parse follows the JSON grammar exactly. It does not accept the looser JavaScript object literal syntax. Each of the following throws a SyntaxError:
const invalid = [
"{a: 1}", // unquoted key
"{'a': 1}", // single quotes
'{"a": 1,}', // trailing comma
'[1, 2,]', // trailing comma in array
'{"a": 01}', // leading zero
'{"a": .5}', // no digit before the decimal point
'{"a": +1}', // leading plus sign
'{"a": NaN}', // NaN is not a JSON value
'{"a": undefined}', // undefined is not a JSON value
'{"a": 1} // note', // comments are not allowed
"" // empty string
];
for (const text of invalid) {
try {
JSON.parse(text);
console.log("accepted:", text);
} catch (err) {
console.log("rejected:", JSON.stringify(text));
}
}Every line prints rejected. Configuration files that allow comments or trailing commas (JSON5, JSONC, tsconfig.json) need a separate parser. The chapter on invalid JSON covers how to catch these errors cleanly.
Numbers and String Escapes
JSON numbers become ordinary JavaScript numbers. Exponents are allowed, and formatting details are not preserved:
console.log(JSON.parse("1e3")); // 1000
console.log(JSON.parse("1.50")); // 1.5
console.log(Object.is(JSON.parse("-0"), -0)); // trueBecause every number becomes a double, integers larger than Number.MAX_SAFE_INTEGER (2^53 − 1) can lose precision without any error. Large IDs are a common victim. That problem has its own chapter.
JSON string escapes are decoded into the characters they stand for:
const text = '{"msg":"line1\\nline2","e":"caf\\u00e9","q":"say \\"hi\\""}';
const obj = JSON.parse(text);
console.log(obj.msg); // line1 (newline) line2
console.log(obj.e); // "café"
console.log(obj.q); // say "hi"The backslashes are doubled in the source because the JavaScript string literal handles one level of escaping. The JSON parser then handles the next. A raw, unescaped newline or tab inside a JSON string is invalid. The text must use \n or \t.
Duplicate Keys and the `__proto__` Key
The JSON specification does not say what should happen with duplicate keys. JavaScript's JSON.parse keeps the last one and gives no warning:
console.log(JSON.parse('{"role":"user","role":"admin"}')); // { role: "admin" }This matters if one part of your system validates the first value and another part uses the last. Different parsers in other languages may resolve duplicates differently.
A key named "__proto__" becomes an ordinary own property. It does not change the object's prototype, which is different from writing { __proto__: ... } as an object literal:
const parsed = JSON.parse('{"__proto__": {"isAdmin": true}}');
console.log(Object.keys(parsed)); // ["__proto__"]
console.log(Object.getPrototypeOf(parsed) === Object.prototype); // true
console.log(parsed.isAdmin); // undefinedJSON.parse itself is safe here. The danger comes later, if your code copies such an object into another one with a naive recursive merge. The security chapter covers that case.
Parsing JSON from Real Sources
Most JSON you parse comes from an HTTP response, a file, or a storage API that holds strings. With fetch, response.json() reads the body and parses it in one step. It returns a promise, and that promise rejects with a SyntaxError if the body is not valid JSON.
// Runs in Node 18+ and modern browsers; Response is built in.
async function demo() {
const ok = new Response('{"status":"ok","count":3}');
const data = await ok.json();
console.log(data.count); // 3
const bad = new Response("<html>Server Error</html>");
try {
await bad.json();
} catch (err) {
console.log(err.name); // "SyntaxError"
}
}
demo();The second case shows a common failure in production. An error page or a proxy returns HTML, and the client tries to parse it as JSON. Check response.ok and the Content-Type header before you call .json(). That way the error you report says what actually went wrong.
To read a file in Node, get the text first and then parse it:
const fs = require("fs");
fs.writeFileSync("settings.json", '{"theme":"dark","fontSize":14}');
const settings = JSON.parse(fs.readFileSync("settings.json", "utf8"));
console.log(settings.theme); // "dark"Pass the "utf8" encoding so that you get a string. Without it, readFileSync returns a Buffer. A Buffer happens to convert to its text content, but relying on that conversion is fragile, and the encoding is just as easy to get wrong.
Double-Encoded JSON
A common bug is calling JSON.stringify on something that is already a JSON string. The result is a JSON string whose content is JSON text, so parsing it once gives you back a string, not an object:
const payload = { a: 1 };
const once = JSON.stringify(payload); // '{"a":1}'
const twice = JSON.stringify(once); // '"{\"a\":1}"'
const step1 = JSON.parse(twice);
console.log(typeof step1); // "string"
console.log(step1.a); // undefined
const step2 = JSON.parse(step1);
console.log(step2.a); // 1If a parsed result is unexpectedly a string that starts with { or [, look for an extra stringify on the sending side. Fix it there instead of adding a second parse on the receiving side. Parsing twice hides the bug and breaks as soon as the sender is corrected.
Summary of Behaviors
| Situation | Result |
|---|---|
| Valid object or array text | New, independent plain structure |
| `"42"`, `"true"`, `"null"` | The corresponding primitive |
| Non-string argument | Converted with `String()` first |
| Already-parsed object | `SyntaxError` (`"[object Object]"`) |
| Duplicate keys | Last value wins |
| ISO date string | Stays a string |
| Invalid syntax or empty string | `SyntaxError` |
Exercise
What does each call print or throw? (1) JSON.parse(" false ") (2) JSON.parse('{"x":1,"x":"one"}').x (3) JSON.parse(JSON.parse('"[1,2]"'))[1] (4) JSON.parse(undefined)
Show answer
(1) false, because surrounding whitespace is ignored and booleans are valid top-level values. (2) "one", because the last duplicate key wins. (3) 2. The first parse returns the string "[1,2]", and the second parse turns that string into an array whose element at index 1 is 2. (4) It throws a SyntaxError, because undefined is converted to the string "undefined", which is not valid JSON.
Exercise
An API returns {"createdAt":"2024-03-01T12:00:00.000Z"}. After const r = JSON.parse(body), the line r.createdAt.getTime() throws a TypeError. Explain why and give the simplest fix that does not use a reviver.
Show answer
JSON has no date type, so createdAt is parsed as a string, and strings have no getTime method. Convert it explicitly after parsing: const created = new Date(r.createdAt); created.getTime();. A reviver can do this conversion automatically during parsing, as a later chapter shows.
Exercise
A teammate's code calls JSON.parse(data) and fails with "Unexpected token o in JSON at position 1". What is the most likely cause, and how would you confirm it?
Show answer
data is probably already an object. String(data) gives "[object Object]", and the o at position 1 is invalid JSON. Confirm it by logging typeof data. If it prints "object", the value was already parsed (for example by response.json() or by framework middleware), and the extra JSON.parse call should be removed.