JSON Reviver
The reviver function in JSON.parse() transforms values during parsing. Use it to revive Date strings into Date objects.
The reviver function in JSON.parse() transforms values during parsing. Use it to revive Date strings into Date objects.
const json = '{"name":"Alice","createdAt":"2024-06-15T10:30:00.000Z"}';
// Without reviver: createdAt is a plain string
const raw = JSON.parse(json);
console.log(raw.createdAt instanceof Date); // false
// With reviver: convert ISO strings to Date objects
const parsed = JSON.parse(json, (key, value) => {
if (typeof value === "string" && /^\d{4}-\d{2}-\d{2}T/.test(value)) {
return new Date(value);
}
return value;
});
console.log(parsed.createdAt instanceof Date); // true
Use a reviver to restore Date objects from JSON — they serialize to strings and lose their Date type otherwise.
More in JavaScript