TExcelTAD
Home › JSON › JSON.parse()

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.

js
JSON.parse(text)
JSON.parse(text, reviver)

Basic use

js · try it yourself
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:

js · try it yourself
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:

js · try it yourself
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 naive JSON.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.

js · try it yourself
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:

js · try it yourself
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?

  1. The string "[1, 2]"
  2. An array with two numbers
  3. An object
  4. A SyntaxError

What happens when JSON.parse receives invalid JSON?

  1. It returns null
  2. It returns undefined
  3. It throws a SyntaxError
  4. It returns the original string

Inside a reviver, what does returning undefined do?

  1. Sets the value to null
  2. Removes that key from the result
  3. Stops parsing
  4. Keeps the original value