JSON.parse()
JSON.parse() converts a JSON string into a JavaScript value. Whenever data arrives as text — from an API, a file, localStorage or a message — this is the function that turns it into something you can work with.
JSON.parse(text)
JSON.parse(text, reviver)Basic use
const text = '{"name": "Hoa", "age": 31, "languages": ["vi", "en"]}';
const person = JSON.parse(text);
console.log(person);
console.log(person.name.toUpperCase());
console.log(person.languages.length);{ name: 'Hoa', age: 31, languages: [ 'vi', 'en' ] }
HOA
2
The result can be any JSON type, not just an object:
console.log(JSON.parse("42"));
console.log(JSON.parse('"hello"'));
console.log(JSON.parse("true"));
console.log(JSON.parse("null"));
console.log(JSON.parse("[1, 2, 3]"));
console.log(JSON.parse(" { } "));42
hello
true
null
[ 1, 2, 3 ]
{}
Always handle errors
If the text is not valid JSON, JSON.parse() throws a SyntaxError. Data from the outside world can always be broken, so wrap the call in try...catch:
function safeParse(text) {
try {
return { ok: true, value: JSON.parse(text) };
} catch (err) {
return { ok: false, error: err.name + ": " + err.message };
}
}
console.log(safeParse('{"valid": true}'));
console.log(safeParse("{'single': 'quotes'}"));
console.log(safeParse(""));{ ok: true, value: { valid: true } }
{
ok: false,
error: "SyntaxError: Expected property name or '}' in JSON at position 1 (line 1 column 2)"
}
{ ok: false, error: 'SyntaxError: Unexpected end of JSON input' }
Note: An empty string is not valid JSON. A server that answers with an empty body (for example
204 No Content) will make a naiveJSON.parse()call fail.
The reviver function
The optional second argument is a reviver: a function called for every key/value pair, from the innermost values outwards. Whatever it returns replaces the value; returning undefined removes the key.
const text = '{"price": "19.50", "qty": "3", "note": "fragile", "internal": "x"}';
const order = JSON.parse(text, (key, value) => {
if (key === "price" || key === "qty") return Number(value); // convert
if (key === "internal") return undefined; // drop
return value; // keep
});
console.log(order);
console.log(order.price * order.qty);{ price: 19.5, qty: 3, note: 'fragile' }
58.5
Watch the call order with a reviver that only logs. The final call has an empty key "" and receives the whole result:
JSON.parse('{"a": 1, "b": {"c": 2}}', function (key, value) {
console.log(JSON.stringify(key), "=>", JSON.stringify(value));
return value;
});"a" => 1
"c" => 2
"b" => {"c":2}
"" => {"a":1,"b":{"c":2}}
A very common use of a reviver is turning date strings back into Date objects — see the JSON and Dates lesson.
Parsing is not the same as eval
Long ago, people "parsed" JSON with eval("(" + text + ")"). Never do that: eval executes any JavaScript in the string, so a malicious response could run code in your page. JSON.parse() only understands data and is also faster.
What JSON.parse does not do
| It does NOT... | Why it matters |
|---|---|
Recreate Date, Map, Set or class instances |
You get plain strings, objects and arrays — use a reviver |
| Validate the shape of the data | {"age": "old"} parses fine; check fields yourself or use JSON Schema |
| Accept comments or trailing commas | Use a JSON5/JSONC parser for config files that need them |
| Keep huge integers exact | Numbers beyond 2^53 lose precision |
Test yourself
What does JSON.parse("[1, 2]") return?
- The string "[1, 2]"
- An array with two numbers
- An object
- A SyntaxError
What happens when JSON.parse receives invalid JSON?
- It returns null
- It returns undefined
- It throws a SyntaxError
- It returns the original string
Inside a reviver, what does returning undefined do?
- Sets the value to null
- Removes that key from the result
- Stops parsing
- Keeps the original value