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.
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
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}' Pretty-Printing
A third argument to stringify is the indent — a number for spaces,
or a string.
const obj = { name: "Ada", roles: ["admin"] };
console.log(JSON.stringify(obj, null, 2));
// {
// "name": "Ada",
// "roles": [
// "admin"
// ]
// } What JSON Cannot Represent
JSON only knows strings, numbers, booleans, null, arrays, and
plain objects. Anything else either gets converted or skipped.
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 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.
const user = { name: "Ada", password: "secret", id: 1 };
console.log(JSON.stringify(user, ["name", "id"]));
// '{"name":"Ada","id":1}' ← password skipped 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 Catching Bad JSON
JSON.parse throws a SyntaxError on bad input. Wrap in
try/catch when the source isn’t trusted.
function safeParse(s) {
try {
return JSON.parse(s);
} catch {
return null;
}
}
console.log(safeParse("not json")); // null
console.log(safeParse('{"x":1}')); // { x: 1 } 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 →