CKTIS / JavaScript
JSON.stringify: a JavaScript value to JSON text
JSON.stringify serializes a JavaScript value to JSON text, with an optional replacer to select or transform data and space to control indentation.
Version: ECMAScript 5 onward; well-formed lone-surrogate escaping from ECMAScript 2019; example target: Node.js 24.22.2
Syntax
JSON.stringify(value[, replacer[, space]])JSON.stringify(value, replacer?, space?) returns a JSON string, or undefined when the top-level value is undefined, a function, or a Symbol. Such values are omitted in an object but become null in an array; NaN and infinities also become null, while -0 is written as 0. It serializes own enumerable string-keyed properties in the defined Object.keys order; Symbol keys are ignored. The own-enumerable description applies to the default property list; a replacer array reads named properties with Get, so it can include an inherited or non-enumerable one.
A toJSON method, when present, runs before the replacer. A replacer function receives (key, value), with this set to the holder, and can replace the value or omit a property by returning undefined; the root call uses the empty key "". A replacer array forms the allowlist of object property names. Numeric space is capped at 10 spaces, while string space is truncated to its first 10 characters. For string space, “10 characters” means exactly the first 10 UTF-16 code units.
A cyclic reference throws TypeError. A BigInt also throws TypeError unless ordinary property lookup finds a callable toJSON; the method may come from a prototype. Exceptions from a getter, toJSON, or the replacer propagate. Stable property order does not make the output canonical JSON for cryptographic signing. The method has been standard since ECMAScript 5; since ECMAScript 2019, lone Unicode surrogates are emitted as \ud800–\udfff escape sequences so the result is well-formed Unicode.
Examples
const value = {
name: "Ada",
missing: undefined,
numbers: [1, NaN, Infinity, undefined],
nested: { keep: true, secret: "hidden" },
};
console.log(JSON.stringify(value, (key, current) =>
key === "secret" ? undefined : current,
));
console.log(JSON.stringify(undefined) === undefined);
try {
JSON.stringify(1n);
} catch (error) {
console.log(error instanceof TypeError);
}
const cycle = {};
cycle.self = cycle;
try {
JSON.stringify(cycle);
} catch (error) {
console.log(error instanceof TypeError);
}Result
{"name":"Ada","numbers":[1,null,null,null],"nested":{"keep":true}}
true
true
true