Sub topic 9
Rebuilding Dates and Custom Types with a Reviver
JSON.stringify flattens rich values into strings, numbers, booleans, null, arrays, and plain objects. When you parse that text back, you only get those same plain types. A Date comes back as an ISO string, and a Money instance comes back as an ordinary object. A reviver is the optional second argument to JSON.parse. It lets you rebuild the original types while parsing.
This chapter assumes you know how JSON.parse and JSON.stringify work, how replacers and toJSON shape output, and how regular functions differ from arrow functions in how they bind this.
How the Reviver Is Called
The reviver has the signature (key, value). JSON.parse first builds the whole plain result. It then walks that result and calls the reviver once for every property and array element. Whatever the reviver returns replaces the value at that position.
Three rules govern the walk:
- Bottom-up order. Children are visited before their parent. When the reviver sees an object, every value inside it has already been revived.
- Keys are strings. Array elements arrive with keys
"0","1", and so on. - The root comes last, with key
"". The final call receives the whole result.thisis a wrapper object{ "": result }.
During every call, this is the object or array that holds the current key, provided you use a regular function.
const text = '{"a":1,"b":{"c":2},"d":[3,4]}';
JSON.parse(text, function (key, value) {
console.log(JSON.stringify(key), "->", JSON.stringify(value));
return value;
});
// "a" -> 1
// "c" -> 2
// "b" -> {"c":2}
// "0" -> 3
// "1" -> 4
// "d" -> [3,4]
// "" -> {"a":1,"b":{"c":2},"d":[3,4]}Return Values: Replace, Keep, or Delete
The reviver's return value decides what ends up in the result:
| Reviver returns | Effect on the result |
|---|---|
| The same `value` | The value stays unchanged |
| A different value | The new value replaces the old one |
| `undefined` on an object property | The property is deleted |
| `undefined` on an array element | The element is deleted, which leaves a hole; the array length stays the same |
| `undefined` for the root (key `""`) | `JSON.parse` returns `undefined` |
The last row causes the most common reviver bug. If a reviver has no return statement on its fallthrough path, every value is deleted and the root becomes undefined:
const broken = JSON.parse('{"a":1,"b":2}', (key, value) => {
if (key === "a") return value * 2;
// missing: return value;
});
console.log(broken); // undefined
const fixed = JSON.parse('{"a":1,"b":2}', (key, value) => {
if (key === "a") return value * 2;
return value;
});
console.log(fixed); // { a: 2, b: 2 }
const holes = JSON.parse("[1,2,3]", (key, value) => (value === 2 ? undefined : value));
console.log(holes, holes.length); // [ 1, <1 empty item>, 3 ] 3Reviving Dates
A Date serializes through its built-in toJSON to a string such as "2024-01-15T09:30:00.000Z". Your reviver has to decide which strings to turn back into Dates. You can make that decision in three main ways.
Strategy 1: Match the string's shape
A regular expression matches anything that looks like an ISO timestamp. This works without knowing the schema, but it produces false positives. A user's comment that happens to be a timestamp, or an ID that looks like one, also becomes a Date.
const isoDate = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/;
const post = JSON.parse(
'{"publishedAt":"2024-01-15T09:30:00.000Z","body":"2024-01-15T09:30:00.000Z"}',
(key, value) => (typeof value === "string" && isoDate.test(value) ? new Date(value) : value)
);
console.log(post.publishedAt instanceof Date); // true
console.log(post.body instanceof Date); // true, which is probably wrongThe regex also misses valid dates written in other formats, such as "2024-01-15T09:30:00+02:00" or values without milliseconds. A strict pattern misses dates you wanted, and a loose pattern catches strings you didn't want.
Strategy 2: Allowlist the keys
If you know the schema, decide by key name. You can then also check that the date is valid. new Date("garbage") does not throw. It produces an Invalid Date, which errors only much later, for example when you call toISOString().
const dateKeys = new Set(["createdAt", "updatedAt"]);
function reviveDates(key, value) {
if (dateKeys.has(key) && typeof value === "string") {
const d = new Date(value);
if (Number.isNaN(d.getTime())) {
throw new TypeError(`Invalid date in "${key}": ${value}`);
}
return d;
}
return value;
}
const user = JSON.parse(
'{"name":"Ada","createdAt":"2024-01-15T09:30:00.000Z","bio":"2024-01-15T09:30:00.000Z"}',
reviveDates
);
console.log(user.createdAt instanceof Date); // true
console.log(typeof user.bio); // "string"
try {
JSON.parse('{"updatedAt":"not a date"}', reviveDates);
} catch (err) {
console.log(err.message); // Invalid date in "updatedAt": not a date
}The key name says nothing about the parent object. A createdAt property at any depth will be converted. If two parts of your data use the same key name with different meanings, check this as well, or use type tags.
Strategy 3: Tag the type explicitly
The most reliable approach records the type in the JSON itself, as in {"__type":"Date","iso":"..."}. The parser then never has to guess. The next section builds this approach.
| Strategy | Needs schema knowledge | False positives | Changes the JSON format | Best for |
|---|---|---|---|---|
| Regex on string shape | No | Yes | No | Quick scripts, trusted data |
| Key allowlist | Yes | Only on key-name clashes | No | API responses with a known shape |
| Type tags | No | Only if real data uses the tag key | Yes | Round trips you control on both ends |
Rebuilding Custom Types with Type Tags
A tagged format needs two halves. The serializer writes a tag, and the reviver reads the tag and calls the right constructor. A class can write its own tag in toJSON. Built-ins like Map, Set, and Date need a replacer.
The replacer has a trap. JSON.stringify calls toJSON before it calls the replacer. By the time your replacer runs, a Date's value is already a string. The original object is still available as this[key], so use a regular function and check that instead.
class Money {
constructor(cents, currency) {
this.cents = cents;
this.currency = currency;
}
toJSON() {
return { __type: "Money", cents: this.cents, currency: this.currency };
}
static fromJSON(obj) {
return new Money(obj.cents, obj.currency);
}
}
function typedReplacer(key, value) {
const raw = this[key]; // the value before toJSON ran
if (raw instanceof Date) return { __type: "Date", iso: raw.toISOString() };
if (raw instanceof Map) return { __type: "Map", entries: [...raw] };
if (raw instanceof Set) return { __type: "Set", values: [...raw] };
return value;
}
const revivers = {
Money: Money.fromJSON,
Date: (obj) => {
const d = new Date(obj.iso);
if (Number.isNaN(d.getTime())) throw new TypeError(`Invalid date: ${obj.iso}`);
return d;
},
Map: (obj) => new Map(obj.entries),
Set: (obj) => new Set(obj.values)
};
function typedReviver(key, value) {
if (
value !== null &&
typeof value === "object" &&
!Array.isArray(value) &&
Object.hasOwn(value, "__type")
) {
const revive = Object.hasOwn(revivers, value.__type) ? revivers[value.__type] : undefined;
if (!revive) throw new TypeError(`Unknown __type: ${value.__type}`);
return revive(value);
}
return value;
}
const order = {
id: 1,
total: new Money(1999, "EUR"),
placedAt: new Date("2024-01-15T09:30:00.000Z"),
tags: new Set(["gift"]),
stock: new Map([["sku-1", 3]])
};
const text = JSON.stringify(order, typedReplacer);
console.log(text);
// {"id":1,"total":{"__type":"Money","cents":1999,"currency":"EUR"},
// "placedAt":{"__type":"Date","iso":"2024-01-15T09:30:00.000Z"},
// "tags":{"__type":"Set","values":["gift"]},
// "stock":{"__type":"Map","entries":[["sku-1",3]]}}
// (printed on one line; wrapped here for reading)
const back = JSON.parse(text, typedReviver);
console.log(back.total instanceof Money); // true
console.log(back.placedAt.getUTCFullYear()); // 2024
console.log(back.tags.has("gift")); // true
console.log(back.stock.get("sku-1")); // 3The bottom-up order is what makes nesting work here. If a Map's entries contained tagged Dates, those Dates would already be real Date objects by the time revivers.Map runs. Each reviver function only needs to handle its own level.
Design details that matter
- Use a registry, not a dynamic lookup. The
reviversobject is an explicit allowlist, andObject.hasOwnstops a tag like"constructor"or"__proto__"from resolving to an inherited property. Never resolve tags withglobalThis[value.__type]or anything similar. That lets the input choose which code runs. The security chapter covers this risk in more depth. - Fail loudly on unknown tags. Throwing on an unknown tag exposes version mismatches between writer and reader. Silently passing the object through hides them. If you need forward compatibility, decide that on purpose and document it.
- Pick a tag key that won't collide. If real user data can contain a
__typeproperty, the reviver will misread it. Choose a more distinctive key, or wrap every tagged value in a structure your data never uses. - Validate the tagged payload.
Money.fromJSONtrusts thatcentsis a number. For data from outside your system, check the fields before you construct the object.
Reviver Gotchas
Arrow functions lose `this`
You can't get the holder object from an arrow function, because arrow functions do not bind their own this. Use a regular function when the decision depends on the parent. One example is converting time only inside objects that also have kind: "event":
const data = JSON.parse(
'{"event":{"kind":"event","time":"2024-01-15T09:30:00.000Z"},"log":{"time":"09:30"}}',
function (key, value) {
if (key === "time" && this.kind === "event") return new Date(value);
return value;
}
);
console.log(data.event.time instanceof Date); // true
console.log(data.log.time); // "09:30"The reviver can see siblings through this. Changing siblings through this is legal but fragile. Depending on order, a sibling you change may or may not have been revived already. Treat this as read-only.
The reviver sees already-parsed numbers
A reviver for a number gets the number after it has been converted to a double. If precision was lost, the reviver cannot get it back from value. Some recent engines pass a third context argument that holds the original source text for primitive values. Check that your runtime supports it before you rely on it.
Cost
The reviver runs once for every value in the document, including every array element. With a large payload, that becomes millions of function calls. Keep the fast path, the final return value, cheap. Do your type checks before any regex or set lookups. If only one small branch of the data needs reviving, parse without a reviver and convert that branch yourself afterward.
Exercises
Exercise
What does JSON.parse('{"x":1,"y":2}', (k, v) => { if (typeof v === "number") return v + 1; }) return, and why?
Show answer
It returns undefined. The reviver returns v + 1 for the numbers, but on the final call (key "", value being the root object) it falls through and returns undefined, which becomes the result of JSON.parse. Add "return v;" at the end to get { x: 2, y: 3 }.
Exercise
A replacer written as (key, value) => value instanceof Date ? { __type: "Date", iso: value.toISOString() } : value never tags any dates. Explain the cause and give the fix.
Show answer
JSON.stringify calls Date.prototype.toJSON before calling the replacer, so value is already an ISO string and never an instance of Date. Use a regular function and inspect the original value: function (key, value) { const raw = this[key]; return raw instanceof Date ? { __type: "Date", iso: raw.toISOString() } : value; }.
Exercise
Serialized data contains a Map whose entries include tagged Dates, such as {"_type":"Map","entries":[["start",{"_type":"Date","iso":"2024-01-15T09:30:00.000Z"}]]}. With the typedReviver from this chapter, is back.get("start") a Date or a plain tagged object? Explain using the reviver's visit order.
Show answer
It is a Date. The reviver works bottom-up, so it revives the inner {"__type":"Date"} object into a Date first. Only after that does it visit the outer Map object, whose entries array already holds the real Date. new Map(obj.entries) therefore receives ["start", Date].
Exercise
Why does the chapter's typedReviver use Object.hasOwn(revivers, value._type) rather than revivers[value._type] alone?
Show answer
Plain objects inherit properties from Object.prototype. A tag such as "constructor" or "toString" would resolve to an inherited function and run unexpected code instead of reaching the "Unknown __type" error. Object.hasOwn limits lookups to the explicitly registered types.