← Back to JavaScript, page 9

javascript-0163 · Easy fresher

How do the JSON.parse reviver and the JSON.stringify replacer and toJSON work, and how do you round-trip dates and Maps?

JSON.parse(text, reviver) calls the reviver for every key and value from the innermost values outward, so you can convert values such as date strings back into Date objects. JSON.stringify(value, replacer, space) lets you filter keys with an array or transform values with a function, and an object's toJSON method controls its own output. Dates become strings, and Map, Set, undefined, and functions need custom handling.

Full answer

JSON is text with a small set of types: objects, arrays, strings, numbers, booleans, and null. JavaScript values outside that set need rules.

JSON.stringify(value, replacer, space):

  • replacer as an array lists the property names that are kept (nested objects use the same list).
  • replacer as a function is called as replacer(key, value) for every pair, with this as the holder, starting with the key '' for the root. Return a new value to change the output, or undefined to drop the property.
  • space (a number or string) pretty-prints.
  • If a value has a toJSON() method, its result is used before the replacer runs. Date has one that returns an ISO string.
  • Defaults: undefined, functions, and symbols are dropped in objects and become null in arrays, NaN and Infinity become null, Map and Set become {}, and BigInt throws a TypeError.

JSON.parse(text, reviver): after parsing, the reviver is called as reviver(key, value) for each property, deepest first and the root last (with key ''). Return a value to replace it, or undefined to delete the property. Because JSON has no date type, dates arrive as strings, so a reviver can detect an ISO pattern and return a Date. Detecting by key name (createdAt) is safer than guessing from the string shape.

Round-tripping other types: write a replacer that tags values, such as { __type: 'Map', entries: [...] }, and a reviver that rebuilds them. For class instances, add a toJSON method and a static fromJSON.

Cautions: JSON.parse throws a SyntaxError on bad input, so wrap it with try. Circular structures throw a TypeError in stringify. Big integers lose precision when parsed as numbers. Never build objects from parsed JSON with unsafe merges (prototype pollution). Use structuredClone when you only need a deep copy within JavaScript.

javascript
const data = { id: 1, name: 'Asha', password: 'secret', createdAt: new Date('2026-03-05T10:30:00Z'), tags: ['a'], skip: undefined, run() {}, score: NaN };
console.log(JSON.stringify(data));
console.log(JSON.stringify(data, ['id', 'name']));
console.log(JSON.stringify(data, (key, value) => (key === 'password' ? undefined : value), 2));
console.log(JSON.stringify([undefined, () => {}, Symbol('s'), NaN, Infinity]));

class Money {
  constructor(cents, currency) { this.cents = cents; this.currency = currency; }
  toJSON() { return { amount: (this.cents / 100).toFixed(2), currency: this.currency }; }
  static fromJSON({ amount, currency }) { return new Money(Math.round(Number(amount) * 100), currency); }
}
console.log(JSON.stringify({ price: new Money(1999, 'USD') }));

const text = JSON.stringify({ when: new Date('2026-03-05T10:30:00Z'), n: 1 });
const plain = JSON.parse(text);
console.log('without a reviver:', typeof plain.when);
const revived = JSON.parse(text, (key, value) => (key === 'when' ? new Date(value) : value));
console.log('with a reviver:', revived.when instanceof Date, revived.when.getUTCFullYear());

const order = [];
JSON.parse('{"a": {"b": 1}, "c": 2}', function (key, value) { order.push(key === '' ? '(root)' : key); return value; });
console.log('reviver order, deepest first:', order);
console.log(JSON.parse('{"keep": 1, "drop": 2}', (key, value) => (key === 'drop' ? undefined : value)));

// Map and Set round trip with tags
const replacer = (key, value) => {
  if (value instanceof Map) return { __type: 'Map', entries: [...value] };
  if (value instanceof Set) return { __type: 'Set', values: [...value] };
  return value;
};
const reviver = (key, value) => {
  if (value && value.__type === 'Map') return new Map(value.entries);
  if (value && value.__type === 'Set') return new Set(value.values);
  return value;
};
const original = { users: new Map([[1, 'Asha']]), ids: new Set([1, 2]) };
console.log(JSON.stringify(original), JSON.stringify(original, replacer));
const restored = JSON.parse(JSON.stringify(original, replacer), reviver);
console.log(restored.users.get(1), restored.ids.has(2), restored.users instanceof Map);

for (const attempt of [() => JSON.stringify({ big: 10n }), () => JSON.parse('{bad json}'), () => { const loop = {}; loop.self = loop; JSON.stringify(loop); }]) {
  try { attempt(); } catch (error) { console.log(error.name); }
}
console.log(JSON.parse('12345678901234567890'));

Run with Node.js v24.22.1 as js-163.js; two runs gave identical output. Output: {"id":1,"name":"Asha","password":"secret","createdAt":"2026-03-05T10:30:00.000Z","tags":["a"],"score":null} {"id":1,"name":"Asha"} { "id": 1, "name": "Asha", "createdAt": "2026-03-05T10:30:00.000Z", "tags": [ "a" ], "score": null } [null,null,null,null,null] {"price":{"amount":"19.99","currency":"USD"}} without a reviver: string with a reviver: true 2026 reviver order, deepest first: [ 'b', 'a', 'c', '(root)' ] { keep: 1 } {"users":{},"ids":{}} {"users":{"__type":"Map","entries":[[1,"Asha"]]},"ids":{"__type":"Set","values":[1,2]}} Asha true true TypeError SyntaxError TypeError 12345678901234567000

Key points

  • Replacer arrays select keys; replacer functions transform or drop values; toJSON runs first.
  • Dates become strings; undefined, functions, and symbols are dropped; NaN becomes null; BigInt throws.
  • The reviver runs deepest first and can convert strings back to Dates; match by key name for safety.
  • Tag Map and Set values in the replacer and rebuild them in the reviver.
  • Wrap parse in try and watch circular data and large integers.

Common mistakes

  • Expecting dates to come back as Date objects without a reviver.
  • Serializing Map or Set directly and getting an empty object.
  • Calling JSON.parse on untrusted text without try and catch.
  • Putting secrets into objects that are later stringified, instead of filtering them.

Follow-ups

  • Why does the reviver run on the deepest values first?
  • How would you handle BigInt values in JSON?
  • What is the difference between JSON.stringify and structuredClone for copying?

Tips

  • Describe replacer and reviver as the two hooks, one for each direction.
  • Give the date example, since it is the most common need.
  • Mention what JSON drops silently.