Sub topic 9
Rebuilding Dates and Custom Types with a Reviver
This chapter assumes you know how JSON.parse works, why JSON.stringify turns a Date into an ISO string, and how toJSON controls what a class instance writes out. A reviver handles the other direction. It turns the plain strings and objects coming out of JSON back into richer values.
What a Reviver Is
A reviver is a function you pass as the second argument to JSON.parse. The parser calls it once for every key/value pair it produces, and the reviver's return value replaces the original value in the result.
const json = '{"name":"launch","at":"2024-01-15T09:30:00.000Z"}';
const isoDate = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/;
const event = JSON.parse(json, (key, value) =>
typeof value === "string" && isoDate.test(value) ? new Date(value) : value
);
console.log(event.at instanceof Date); // true
console.log(event.at.getUTCFullYear()); // 2024Without the reviver, event.at would stay a string. Calling .getUTCFullYear() on it would throw a TypeError.
The Working Model: Bottom-Up Traversal
The reviver runs after parsing has built the whole structure. It walks the tree depth-first and visits children before their parents. The final call uses the empty string "" as the key and the entire result as the value. Inside a regular function reviver, this is the object or array that holds the current key.
JSON.parse('{"a":{"b":1},"c":[2]}', (key, value) => {
console.log(JSON.stringify(key));
return value;
});
// "b"
// "a"
// "0"
// "c"
// ""Bottom-up order matters for custom types. When the reviver sees a parent object, that object's children have already been revived.
Reviving Custom Types with a Type Tag
Matching values by their shape is fragile. A cleaner pattern has toJSON write a type tag, and the reviver looks for that tag:
class Money {
constructor(cents, currency) {
this.cents = cents;
this.currency = currency;
}
format() {
return `${(this.cents / 100).toFixed(2)} ${this.currency}`;
}
toJSON() {
return { __type: "Money", cents: this.cents, currency: this.currency };
}
}
function reviver(key, value) {
if (value && typeof value === "object" && value.__type === "Money") {
return new Money(value.cents, value.currency);
}
return value;
}
const text = JSON.stringify({ items: [{ price: new Money(1999, "EUR") }] });
const order = JSON.parse(text, reviver);
console.log(order.items[0].price instanceof Money); // true
console.log(order.items[0].price.format()); // "19.99 EUR"The reviver goes through toJSON, so the tag stays the same in both directions.
Common Errors
| Mistake | Symptom | Fix |
|---|---|---|
| Forgetting to `return value` for keys you don't handle | Properties vanish | Always end with `return value` |
| Returning `undefined` by accident | The property is deleted from the result | Return `undefined` only when you mean to drop the key |
| Converting every date-shaped string | A user's bio "2024-01-15T09:30:00.000Z" becomes a `Date` | Convert by key name or by type tag |
| Expecting parents to be visited first | The parent logic sees already-revived children | Write the logic with bottom-up order in mind |
Dropping Fields While Parsing
When the reviver returns undefined, the parser deletes that key. You can use this to remove internal fields:
const clean = JSON.parse('{"id":1,"_debug":"x"}', (key, value) =>
key.startsWith("_") ? undefined : value
);
console.log(clean); // { id: 1 }Exercise
You parse '{"created":"2024-01-15T09:30:00.000Z","note":"2024-01-15T09:30:00.000Z"}' with the regex-based date reviver above. What are the types of created and note, and how would you change the reviver so that only created becomes a Date?
Show answer
Both become Date objects because both strings match the regex. To convert only created, check the key: (key, value) => key === "created" && typeof value === "string" ? new Date(value) : value.
Exercise
In what order does a reviver see the keys of '{"x":[{"y":1}]}', and what key does the last call receive?
Show answer
The order is "y", "0", "x", and then "" for the root. The last call receives the empty string as the key and the whole parsed object as the value.