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 2Broken 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
nullDates
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 10Common 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:
SyntaxErrorFunctions used in this recipe
- JSON.parse — Parses a JSON string and returns the value.
- JSON.stringify — Converts a value to a JSON string.