JavaScript › JSON & Data Serialization

How does the reviver function in JSON.parse() work?

Intermediate

Answer

The optional second argument to JSON.parse() is called for every key/value pair as the object is being built, bottom-up, and its return value replaces the original — letting you transform values (like converting date strings back into Date objects) during parsing.
const json = '{"createdAt":"2026-08-08T00:00:00.000Z"}';
const obj = JSON.parse(json, (key, value) =>
  key === 'createdAt' ? new Date(value) : value
);
console.log(obj.createdAt instanceof Date); // true
Real-world example Automatically converting known date-string fields back into real Date objects right when parsing an API response.

Common follow-ups: Is the reviver called on the top-level object itself, or only on its properties?