JavaScript JSON

Parse, Stringify, and the Gotchas In Between

JavaScript JSON

`JSON.parse` and `JSON.stringify` move data between JavaScript values and strings. Know what survives the round trip.

4 min read Level 1/5 #JSON#parse#stringify
What you'll learn
  • Parse a JSON string and stringify a value
  • Use replacer/reviver for control
  • Recognize what JSON cannot represent

JSON is a text format for data. JavaScript talks JSON through two methods on the global JSON object.

The Two Operations

Parse and stringify script.js
const text = '{"name":"Ada","age":36}';
const obj = JSON.parse(text);
console.log(obj.name);                    // "Ada"

const back = JSON.stringify(obj);
console.log(back);                         // '{"name":"Ada","age":36}'
▶ Preview: console

Pretty-Printing

A third argument to stringify is the indent — a number for spaces, or a string.

Indented output script.js
const obj = { name: "Ada", roles: ["admin"] };
console.log(JSON.stringify(obj, null, 2));
// {
//   "name": "Ada",
//   "roles": [
//     "admin"
//   ]
// }
▶ Preview: console

What JSON Cannot Represent

JSON only knows strings, numbers, booleans, null, arrays, and plain objects. Anything else either gets converted or skipped.

Things that disappear script.js
const data = {
  when: new Date(),       // becomes a string
  ok: true,
  count: NaN,             // becomes null
  bad: undefined,         // omitted
  greet: () => "hi",      // omitted (functions)
  id: 10n,                // throws — BigInt isn't representable
};

console.log(JSON.stringify(data));
// {"when":"2026-…","ok":true,"count":null}  ← function gone, undefined gone
▶ Preview: console

Replacer and Reviver

The second argument to stringify is a replacer — a function or array that filters / transforms. The second argument to parse is a reviver that transforms after parsing.

Pick fields with a replacer array script.js
const user = { name: "Ada", password: "secret", id: 1 };
console.log(JSON.stringify(user, ["name", "id"]));
// '{"name":"Ada","id":1}'   ← password skipped
▶ Preview: console
Revive dates script.js
const text = '{"when":"2026-01-01T00:00:00.000Z"}';
const data = JSON.parse(text, (key, value) => {
  if (key === "when") return new Date(value);
  return value;
});
console.log(data.when instanceof Date);   // true
▶ Preview: console

Catching Bad JSON

JSON.parse throws a SyntaxError on bad input. Wrap in try/catch when the source isn’t trusted.

Defensive parse script.js
function safeParse(s) {
  try {
    return JSON.parse(s);
  } catch {
    return null;
  }
}

console.log(safeParse("not json"));   // null
console.log(safeParse('{"x":1}'));    // { x: 1 }
▶ Preview: console

Up Next

Most apps need to remember things between page loads. Local storage is the simplest option — and JSON is how you put complex values in.

JavaScript Local Storage →