How to Parse JSON in JavaScript
JavaScript has native JSON support built in through the global JSON object. Use JSON.parse to turn a JSON string into an object and JSON.stringify to serialize back to a string.
Parse a JSON string
JSON.parse takes a string and returns the corresponding JavaScript value (object, array, number, string, boolean, or null).
javascript
const text = '{"name":"Ada","roles":["admin","dev"]}';
const data = JSON.parse(text);
console.log(data.name); // "Ada"
console.log(data.roles[0]); // "admin"Stringify a value to JSON
JSON.stringify serializes a value. Pass a third argument to pretty-print with indentation.
javascript
const obj = { name: "Ada", active: true };
const compact = JSON.stringify(obj); // {"name":"Ada","active":true}
const pretty = JSON.stringify(obj, null, 2); // indented with 2 spacesHandle parse errors safely
JSON.parse throws a SyntaxError on invalid input. Wrap it in try/catch so malformed data never crashes your app.
javascript
function safeParse(text) {
try {
return { ok: true, value: JSON.parse(text) };
} catch (err) {
return { ok: false, error: err.message };
}
}Reviver and replacer functions
The optional reviver (parse) and replacer (stringify) let you transform values — for example converting date strings to Date objects or omitting sensitive fields.
javascript
// Revive ISO date strings into Date objects
const data = JSON.parse(text, (key, value) =>
key === "createdAt" ? new Date(value) : value
);
// Omit the password field when serializing
const safe = JSON.stringify(user, (k, v) => (k === "password" ? undefined : v));