JSON.stringify() Explained: replacer, space, toJSON and What Gets Dropped
How JSON.stringify really behaves: the replacer and space arguments, toJSON, and what happens to undefined, dates, Maps, BigInt and circular references.
The signature most people only half use
JSON.stringify(value, replacer, space) turns a JavaScript value into JSON text. Most code only ever passes the first argument, which is fine until a field silently disappears, a date comes back as a string, or the call throws on a value nobody expected to be there.
JSON.stringify({ id: 1, tags: ['a', 'b'] });
// '{"id":1,"tags":["a","b"]}'
JSON.stringify({ id: 1 }, null, 2);
// '{\n "id": 1\n}'The output is always a string (or undefined, see below). Everything that is not plain data — functions, class instances with private state, prototype methods — either gets converted, gets dropped, or throws.
What happens to each kind of value
| Value | Inside an object | Inside an array | At the top level |
|---|---|---|---|
undefined | Key is omitted | null | undefined (not a string) |
| Function, Symbol | Key is omitted | null | undefined |
NaN, Infinity | null | null | "null" |
Date | ISO string via toJSON() | ISO string | ISO string |
Map, Set | {} | {} | "{}" |
BigInt | Throws TypeError | Throws TypeError | Throws TypeError |
| Circular reference | Throws TypeError | Throws TypeError | — |
The asymmetry between objects and arrays exists because arrays cannot have holes in JSON: dropping an element would shift every index after it, so null is used as a placeholder instead.
Silent data loss: the undefined and Date traps
The most common production bug is a field that is undefined on the client and therefore never reaches the server. The API then cannot distinguish "the user cleared this field" from "the client did not send it".
JSON.stringify({ name: 'Ada', nickname: undefined });
// '{"name":"Ada"}' <- nickname is gone
JSON.stringify({ name: 'Ada', nickname: null });
// '{"name":"Ada","nickname":null}'If clearing a value matters to your API, send null explicitly. Dates have the opposite problem: they are serialized, but they do not come back. Date.prototype.toJSON produces an ISO 8601 string, and JSON.parse has no way to know that string used to be a date.
const copy = JSON.parse(JSON.stringify({ at: new Date(0) }));
typeof copy.at; // 'string' -> '1970-01-01T00:00:00.000Z'This is also why JSON.parse(JSON.stringify(obj)) is a poor deep clone. Use structuredClone(obj), which keeps dates, Maps, Sets and circular references.
The replacer argument: filter or transform values
The second argument can be an array or a function. An array is an allowlist of property names, applied at every level of nesting:
const user = { id: 7, email: 'a@b.c', passwordHash: 'x', profile: { id: 3, bio: 'hi' } };
JSON.stringify(user, ['id', 'email', 'profile']);
// '{"id":7,"email":"a@b.c","profile":{"id":3}}' <- bio is dropped tooA function receives every key and value, starting with an empty key for the root value. Whatever it returns is serialized instead; returning undefined removes the key. This is the standard way to make BigInt serializable or to redact secrets in logs:
const SECRET_KEYS = new Set(['password', 'token', 'authorization']);
JSON.stringify(payload, (key, value) => {
if (typeof value === 'bigint') return value.toString();
if (SECRET_KEYS.has(key.toLowerCase())) return '[redacted]';
return value;
});Note that the replacer runs after toJSON: for a Date, the value it receives is already the ISO string.
The space argument: readable output
A number from 1 to 10 indents with that many spaces (larger numbers are clamped to 10). A string, such as '\t', is used as the indent itself, truncated to 10 characters. Anything else, including 0, produces compact output.
JSON.stringify(data, null, 2); // two spaces JSON.stringify(data, null, '\t'); // tabs
Use indentation for logs that humans read and for files committed to git; keep compact output for anything sent over the network.
toJSON: let an object decide how it is serialized
If a value has a toJSON() method, JSON.stringify calls it and serializes the result. That is how Date works, and you can use it for your own classes:
class Money {
constructor(cents, currency) { this.cents = cents; this.currency = currency; }
toJSON() { return { amount: (this.cents / 100).toFixed(2), currency: this.currency }; }
}
JSON.stringify({ total: new Money(1999, 'EUR') });
// '{"total":{"amount":"19.99","currency":"EUR"}}'Keep toJSON free of side effects and cheap: it runs every time the object is logged or sent.
Errors you will meet and how to fix them
- TypeError: Converting circular structure to JSON — an object references itself, often a DOM node, a request object, or a parent/child pair. Serialize only the fields you need, or use a replacer that tracks seen objects with a
WeakSetand returns'[Circular]'. - TypeError: Do not know how to serialize a BigInt — convert BigInt to a string in a replacer (as above) or add
toJSONon the value. Sending it as a number would lose precision anyway. - An empty object
{}where data was expected — usually a Map, Set, or class with only private (#field) or non-enumerable properties. Convert first:Object.fromEntries(map)or[...set]. - A string full of backslashes — the value was already a JSON string and got stringified again. See the guide on escaped and double-encoded JSON.
Key order and deterministic output
Keys are written in property order: integer-like keys first in ascending order, then string keys in insertion order. Two objects with the same data but built in a different order therefore produce different strings, which breaks hashing, caching and snapshot tests.
function stableStringify(value) {
return JSON.stringify(value, (_key, v) =>
v && typeof v === 'object' && !Array.isArray(v)
? Object.fromEntries(Object.entries(v).sort(([a], [b]) => a.localeCompare(b)))
: v
);
}When you need a string to embed inside another JSON document, stringify the value a second time on purpose — that is what the JSON Stringify tool does — and decode it with two JSON.parse calls on the other side.