Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to parse a JSON string

Short answer

JSON.parse() turns a JSON string into an object or an array:

const text = '{"name":"Anna","tags":["admin","editor"]}';
const user = JSON.parse(text);
 
console.log(user.name, user.tags.length);

Output:

Anna 2

Broken JSON

If the string is not valid JSON, JSON.parse() throws an error. Wrap it in try...catch:

const safeParse = (text, fallback = null) => {
  try {
    return JSON.parse(text);
  } catch {
    return fallback;
  }
};
 
console.log(safeParse('{"ok":true}').ok);
console.log(safeParse('{ok: true}'));

Output:

true
null

Dates

JSON has no dates, they come as strings. The second argument of JSON.parse(), a reviver function, can convert them while parsing:

const text = '{"title":"Meeting","at":"2025-06-01T10:00:00Z"}';
const event = JSON.parse(text, (key, value) => (key === 'at' ? new Date(value) : value));
 
console.log(event.at instanceof Date, event.at.getUTCHours());

Output:

true 10

Common mistake

JSON requires double quotes around keys and strings. Single quotes, which are fine in JavaScript, break it:

try {
  JSON.parse("{'name': 'Anna'}");
} catch (error) {
  console.log(error.name);
}

Output:

SyntaxError

Functions used in this recipe

Thanks for reading!

Donate to the site — we work hard for you.