How to Parse JSON in JavaScript

← All guides

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 spaces

Handle 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));

Frequently Asked Questions

With fetch, call await response.json() — it reads the body and runs JSON.parse for you. For raw strings use JSON.parse directly.

The input isn't valid JSON — common causes are single quotes, trailing commas, comments, or an unquoted key. Paste it into the JSON Validator to find the exact line.

Use JSON.stringify(value, null, 2) for two-space indentation, or pass a tab character for tab indentation.

Related Tools