Back to results for “JSON”
JavaScript › JSON & Data Serialization

How do you use the replacer parameter of JSON.stringify() to control what gets serialized?

Intermediate

Answer

The second argument can be an array of allowed key names, or a function called for every key/value pair that returns the value to use (or undefined to omit that key) — giving fine-grained control over the output, like excluding sensitive fields.
const user = { name: 'Sam', password: 'secret123' };
JSON.stringify(user, (key, value) => key === 'password' ? undefined : value);
// '{"name":"Sam"}'
Real-world example Excluding a password or internal-only field before sending a user object to a client or logging it.

Common follow-ups: How does the 'space' third argument to JSON.stringify() affect the output?