JSON Replacer
The replacer argument in JSON.stringify() filters or transforms values. Pass an array of key names or a function.
The replacer argument in JSON.stringify() filters or transforms values. Pass an array of key names or a function.
const data = { id: 1, name: "Alice", password: "secret", age: 30 };
// Array replacer — include only these keys
JSON.stringify(data, ["id", "name", "age"]);
// {"id":1,"name":"Alice","age":30}
// Function replacer — custom transformation
JSON.stringify(data, (key, value) => {
if (key === "password") return undefined; // Omit passwords
if (typeof value === "number") return value * 2; // Double numbers
return value;
});
// {"id":2,"name":"Alice","age":60}
Use a function replacer to sanitize sensitive fields like passwords and tokens before JSON serialization.
More in JavaScript