Sub topic 6
Filtering and Transforming Output with a Replacer
This chapter assumes you already know how JSON.stringify serializes objects and arrays, and how it handles values like undefined and functions. The second argument to JSON.stringify is the replacer. It lets you decide which properties appear in the output and what value each one gets. It accepts two forms: a function, which can filter and transform, and an array, which only filters.
The replacer function
A replacer function receives (key, value) for every property that JSON.stringify visits. Whatever the function returns is serialized in place of the original value:
- Return
valueunchanged to keep it. - Return a different value to replace it.
- Return
undefinedto drop the property.
const account = { id: 7, user: "ada", password: "secret" };
const redacted = JSON.stringify(
account,
(key, value) => (key === "password" ? undefined : value),
2
);
console.log(redacted);
// {
// "id": 7,
// "user": "ada"
// }The third argument (2) indents the output. The next chapter covers it.
The replacer is called recursively, starting with the root
The first call is not for a real property. JSON.stringify wraps your value in a holder object { "": value } and calls the replacer with the key "" and the whole value. After that, it walks every nested object and array. For array elements, the key is the index as a string.
const order = {
id: 1,
customer: { name: "Ada", password: "x" },
items: [{ sku: "A1", price: 5 }]
};
const visited = [];
JSON.stringify(order, (key, value) => {
visited.push(key);
return value;
});
console.log(visited);
// ["", "id", "customer", "name", "password", "items", "0", "sku", "price"]Because of this recursion, the redaction example above also removes a password nested at any depth. If your replacer returns a new object, JSON.stringify walks into that new object as well.
Transforming values
A replacer can also reshape data, for example by rounding numbers or masking strings:
const reading = { sensor: "t1", celsius: 21.456789, notes: ["ok", "skip", "ok"] };
const out = JSON.stringify(reading, (key, value) => {
if (typeof value === "number") return Math.round(value * 10) / 10;
if (value === "skip") return undefined;
return value;
});
console.log(out);
// {"sensor":"t1","celsius":21.5,"notes":["ok",null,"ok"]}Returning undefined for an array element produces null, not a shorter array. Array positions are preserved.
Common errors with replacer functions
| Mistake | Result | Fix |
|---|---|---|
| Filtering on `typeof value === "object"` | The root is an object, so the whole result is `undefined` | Check `key !== ""` before dropping values |
| Forgetting to return `value` at the end | Every property is dropped | Always end with `return value` |
| Expecting `value` to be the raw Date | `value` is already the ISO string, because `toJSON` runs before the replacer | Read the original through `this[key]` in a regular `function` |
| Using an arrow function and `this` | `this` is not the holder object | Use `function (key, value) { ... }` |
The replacer array
If you pass an array of strings (numbers are converted to strings), it works as an allowlist. Only those property names are kept, and they are written in the order the array lists them.
const doc = {
secret: "s",
id: 1,
user: { id: 9, name: "Ada", email: "[email protected]" }
};
console.log(JSON.stringify(doc, ["id", "user"]));
// {"id":1,"user":{"id":9}}The list applies at every nesting level. That is why user.name disappeared: "name" is not in the list. To keep it, add "name" to the array, and remember that it will then also be kept on any other object that has a name. The allowlist never removes array elements, because indices are not filtered.
Exercise
What does JSON.stringify({ a: 1, b: { a: 2, c: 3 }, c: [4, 5] }, ["c", "a"]) return, and why?
Show answer
It returns {"c":[4,5],"a":1}. The allowlist keeps only "c" and "a", in that order, so "b" is dropped at the top level. The array under "c" keeps both elements because array indices are never filtered by a replacer array.
Exercise
A developer writes JSON.stringify(data, (k, v) => (typeof v === "object" ? undefined : v)) to strip nested objects, but gets undefined back. Explain the cause and fix it.
Show answer
The first replacer call uses key "" with the entire data object as the value. That value is an object, so the function returns undefined and the whole result becomes undefined. The fix is to exempt the root: (k, v) => (k !== "" && typeof v === "object" && v !== null ? undefined : v).