Customize JSON.stringify with a replacer
How the JSON.stringify replacer works, with checked examples: filtering keys, converting BigInt, Map and Date values, edge cases that change meaning, and when a plain call is the better choice.
JSON.stringify accepts an optional second argument, the replacer, that controls which values are written and how they are converted. This review explains what that argument changes in the output, where it can quietly alter meaning, and when a plain call or a separate transformation step is the better choice. The behavior described here follows the ECMAScript specification and standard JavaScript engines. No environment-specific test results are included.
Is a replacer suitable for your use?
A replacer is a good fit when you need to shape serialized output in one pass. Common cases are dropping sensitive or noisy fields, converting types JSON cannot represent (BigInt, Map, Set), or normalizing values such as dates. Its main benefit is that the source object stays untouched while the output string changes. The main tradeoff is that the changes are one-way and easy to get subtly wrong. Omitted keys, values turned into null and types converted to strings do not come back when the text is parsed, unless you write a matching reviver for JSON.parse.
A plain JSON.stringify call is the better choice when the data already contains only JSON-safe values and must round-trip exactly. It is also preferable when other people need to predict the output without reading your replacer. If you only want readable indentation, use the third argument, space, and pass null as the replacer.
What the replacer actually changes
The replacer changes the serialized text, not the original data, unless your replacer function mutates objects itself, which it should not. It comes in two forms: a function or an array. The space argument is separate. It adds whitespace and changes only how the text looks. Parsing indented and compact output produces the same values.
Function form
The function is called once for every key and value, including nested ones. It receives the key as a string (array indexes arrive as "0", "1" and so on) and the value about to be written. Whatever it returns gets serialized in place of the value. If it returns undefined, a function or a symbol, the property is left out of an object.
const user = { name: "Ada", password: "hunter2", age: 36 };
JSON.stringify(user, (key, value) =>
key === "password" ? undefined : value
);
// {"name":"Ada","age":36}
Array form
An array of strings or numbers works as an allowlist of property names. Only listed keys are kept, and keys appear in the output in the order the array lists them. The list applies to object properties at every depth, not only the top level. Array elements are not filtered by it.
JSON.stringify(user, ["name", "age"]);
// {"name":"Ada","age":36}
The space argument (formatting only)
JSON.stringify({ a: 1, b: [2] }, null, 2);
// {
// "a": 1,
// "b": [
// 2
// ]
// }
A number sets the indent width and is capped at 10. A string such as a tab character is used as the indent, and only its first 10 characters count. None of this affects which values are written.
Edge cases that change meaning
Most surprises come from a few documented rules. Each one is shown below with the output it produces.
The first call is for the whole value
Before visiting any properties, the replacer is called with an empty-string key and the entire input as the value. A replacer that drops all objects therefore drops the root as well. In that case JSON.stringify returns undefined instead of a string.
JSON.stringify({ a: 1 }, (key, value) =>
typeof value === "object" ? undefined : value
);
// undefined (not a string)
Guard on the key (for example, key === "" returns value unchanged) if your filter could match the top-level value.
Inside arrays, omitted values become null
Returning undefined removes an object property. Inside an array, the same return value produces null, so the array length and positions stay the same. Code that reads the result may treat null as real data.
JSON.stringify([1, "a", 2], (key, value) =>
typeof value === "string" ? undefined : value
);
// [1,null,2]
An allowlist must include nested key names
Because the array form applies at every depth, listing only top-level keys empties nested objects.
const order = { id: 7, customer: { name: "Ada", tier: "gold" } };
JSON.stringify(order, ["id", "customer"]);
// {"id":7,"customer":{}}
JSON.stringify(order, ["id", "customer", "name"]);
// {"id":7,"customer":{"name":"Ada"}}
toJSON runs before the replacer
If a value has a toJSON method, as Date does, that method runs first. The replacer then receives its result. A Date therefore reaches the replacer as an ISO string, not as a Date. To reach the original value, use a regular function (not an arrow function) and read this[key], where this is the object that holds the property.
const event = { at: new Date(0) };
JSON.stringify(event, function (key, value) {
if (this[key] instanceof Date) return this[key].getTime();
return value;
});
// {"at":0}
Converting types JSON cannot represent
A BigInt makes JSON.stringify throw a TypeError unless a toJSON method or the replacer converts it first. Map and Set objects do not throw; they serialize as an empty object, which silently loses their contents. A replacer can fix both. The result is still a lossy change: a BigInt written as a string reads back as a string, and a Map written as an object reads back as a plain object.
JSON.stringify({ id: 10n }, (key, value) =>
typeof value === "bigint" ? value.toString() : value
);
// {"id":"10"}
JSON.stringify({ tags: new Map([["a", 1]]) }, (key, value) =>
value instanceof Map ? Object.fromEntries(value) : value
);
// {"tags":{"a":1}}
Object.fromEntries only produces a faithful result when the Map keys are strings or values that are fine as strings. For other key types, write the entries as an array of pairs instead, for example with Array.from(value).
Circular references
A circular structure makes JSON.stringify throw a TypeError. A common workaround is to track visited objects in a WeakSet created fresh for each call. This approach also replaces any object that appears more than once without being circular, such as one config object shared by two parents. The second occurrence is replaced even though no cycle exists. That is a change in meaning, not only in formatting.
const seen = new WeakSet();
JSON.stringify(data, (key, value) => {
if (typeof value === "object" && value !== null) {
if (seen.has(value)) return "[Circular]";
seen.add(value);
}
return value;
});
Editing strings: emoji and combining marks
Replacers are sometimes used to truncate or mask long strings. JavaScript string methods such as slice count UTF-16 code units, not visible characters. Many emoji take two code units, so cutting by length can leave half of one. Engines that implement the ES2019 well-formed JSON.stringify behavior write the leftover lone surrogate as an escape sequence. The output stays valid JSON, but the character is broken.
JSON.stringify({ note: "ok 👍" }, (key, value) =>
typeof value === "string" ? value.slice(0, 4) : value
);
// {"note":"ok \ud83d"}
JSON.stringify({ note: "ok 👍" }, (key, value) =>
typeof value === "string" ? Array.from(value).slice(0, 4).join("") : value
);
// {"note":"ok 👍"}
Array.from splits a string into code points, which keeps single emoji like the one above intact. It can still split sequences that display as one character but contain several code points. Examples are a letter followed by a combining accent, or an emoji joined with others by zero-width joiners. If cuts must respect what readers see as one character, segment by grapheme with Intl.Segmenter. Without a replacer, JSON.stringify leaves emoji and other non-ASCII characters as they are.
Will the output stay usable after copying or sharing?
As long as the replacer returns values JSON can represent, the result is ordinary JSON text. Any standards-compliant parser can read it, and it copies and pastes like any other plain text. The usability questions are less about the characters and more about what the reader can no longer recover.
- Round-trip loss: omitted keys, nulls created in arrays and converted types are not restored by JSON.parse. If the receiver needs the original types, pair the replacer with a reviver, or document the conversions.
- Redaction is not a security control: a replacer that matches the key "password" misses "Password", "pwd" and secrets inside other strings. An allowlist (array form) fails safer than a blocklist, but review it whenever the data shape changes.
- Whitespace handling depends on the destination: indented output relies on newlines and spaces or tabs. Whether a given chat tool, ticket system or editor keeps them was not tested for this article. Compact output (no space argument) is safer where whitespace may be collapsed.
- Key order: with an array replacer, keys follow the array order. With a function replacer, they follow the object's own property order, in which integer-like keys come first. Consumers should not rely on order unless you control both ends.
- Search and diffing: a replacer that renames, masks or reorders fields can make the output harder to match against logs or earlier snapshots. Keep an unmodified version where traceability matters.
Accessibility: no documentation or scoped tests about how specific screen readers announce indented or compact JSON were available for this review, so no claim is made about any particular assistive technology. When JSON is shown to people rather than programs, a short plain-language summary of the important fields alongside the raw text is a reasonable fallback.
When to skip the replacer
If the transformation is more than a few simple rules, a separate step is usually easier to read and test than one replacer that handles every case. That step might map the object to a plain data-transfer shape, or define a toJSON method on your own classes. Use the replacer for narrow, predictable changes. Leave it out when the goal is only readable formatting or exact round-tripping, and pass null with a space value instead.