JavaScript JSON.stringify Replacer: Select Fields
Quick answer
A replacer controls which values appear in serialized JSON and how they are represented. It can be a function or a property-name list.
How it works
Use a function (key, value) to transform values, or an array of allowed property names to select object keys across nesting levels. A function returning undefined omits object properties but creates null for array positions. A replacer function sees values after applicable toJSON calls. space is independent of filtering. Build a deliberate public data object for security-sensitive disclosure rather than rely on a denylist alone.
console.log(JSON.stringify({name:"pen",cost:4,qty:2},["name","qty"]));Expected output in Node.js:
{"name":"pen","qty":2}The property list selects allowed keys.
console.log(JSON.stringify({id:9n},(k,v)=>typeof v==="bigint"?String(v):v));Expected output in Node.js:
{"id":"9"}The replacer converts BigInt to a string before JSON encoding.
Common mistakes
A property-list replacer is not a schema validator and does not select array positions.
Practice
Produce a public JSON record containing only name and quantity from a flat inventory record.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
JavaScript JSON.stringify Replacer: Select Fields — Knowledge Check
Apply the taught concept and predict the output.
What does an array-valued JSON.stringify replacer select?
When is an applicable toJSON transformation relative to a replacer function?
How should you approach releasing only approved sensitive-record fields?
What is the exact console output in JavaScript JSON.stringify Replacer: Select Fields example 1?
console.log(JSON.stringify({name:"pen",cost:4,qty:2},["name","qty"]));What is the exact console output in JavaScript JSON.stringify Replacer: Select Fields example 2?
console.log(JSON.stringify({id:9n},(k,v)=>typeof v==="bigint"?String(v):v));