JavaScript JSON in Depth
JSON.parse and JSON.stringify take extra functions that change the conversion. A reviver runs while parsing, and a replacer runs while writing.
A reviver rebuilds a date
The reviver checks each key as parsing runs. For the date key it builds a real Date object.
const text = '{"title":"Launch","date":"2026-11-08T09:00:00.000Z"}';
const reviver = (key, value) => {
if (key === "date") { return new Date(value); }
return value;
};
const event = JSON.parse(text, reviver);
console.log(event.date instanceof Date);
console.log(event.title);A replacer hides a field
The replacer checks each key as writing runs. For the password key it returns undefined, so the field is dropped.
const user = { name: "Ana", password: "secret123", age: 30 };
const replacer = (key, value) => {
if (key === "password") { return undefined; }
return value;
};
console.log(JSON.stringify(user, replacer));A replacer as a key list
A replacer can be an array of key names instead of a function. Only the listed keys are kept.
const user = { name: "Ana", password: "secret123", age: 30 };
console.log(JSON.stringify(user, ["name", "age"]));Example
const text = '{"name":"Ana","joined":"2024-03-01T00:00:00.000Z","password":"secret123"}';
const reviver = (key, value) => {
if (key === "joined") { return new Date(value); }
return value;
};
const user = JSON.parse(text, reviver);
console.log(user.joined instanceof Date);
const replacer = (key, value) => {
if (key === "password") { return undefined; }
return value;
};
console.log(JSON.stringify(user, replacer));Key points
- Reviver: a function that runs for each value while JSON.parse reads text
- Replacer: a function that runs for each value while JSON.stringify writes text
- A reviver can turn a date string back into a Date object.
- A replacer that returns undefined drops that field from the output.
- A replacer can also be an array of key names to keep.
- JSON text cannot hold a Date, so the reviver rebuilds it after parsing.
In this example, the reviver turns the joined string into a Date while parsing. The first log proves the rebuild worked. The replacer then drops the password field while writing the object back to JSON text.
Try it Yourself
Edit the code, then press Run.
Runs in your browser — the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.
Exercise
What does a reviver do?