JSON.parse and JSON.stringify
- Version
- es2025
- Review
- Draft
Summary#
JSON.stringify turns supported JavaScript values into JSON text. It returns undefined for a top-level value such as undefined or a function. JSON.parse reads JSON text back and throws a SyntaxError when the text is invalid.
Syntax#
const text = JSON.stringify(value, replacer, space);
const data = JSON.parse(text, reviver);
Example#
const fields = ["at", "skipped", "ratio", "list"];
const text = JSON.stringify(
{ at: new Date(0), skipped: undefined, ratio: NaN, list: [undefined] },
fields
);
console.log(text);
const data = JSON.parse(text, (key, value) =>
key === "at" ? new Date(value) : value
);
console.log(data.at.getUTCFullYear());
try {
JSON.parse("{name: 1}");
} catch (error) {
console.log(error instanceof SyntaxError && error.name);
}
Expected output#
{"at":"1970-01-01T00:00:00.000Z","ratio":null,"list":[null]}
1970
SyntaxError
Common mistakes#
A JSON round trip is lossy: dates return as strings unless revived, undefined object properties disappear, and Map or Set contents are not written. By default, serializing a BigInt or following a circular reference throws a TypeError. Validate parsed external data before trusting its shape.
Version applicability#
ECMAScript 5 introduced both functions. The example uses ES2015 const and an arrow function. The replacer array specifies the order of the serialized fields.
Sources#
- Attribution
- DevLookup contributors
- License
- CC-BY-4.0