Skip to content
Tutorials Center
My learning

Topics

Lesson 6 of 39 ยท JSON

Revivers, Replacers and toJSON

Transform data while parsing and serializing JSON: revivers, replacer functions and toJSON. Handle dates, Map, Set, BigInt and circular references.

JSON only knows six types, but your programs use more: dates, maps, sets, big integers and your own classes. When data crosses the network those types get flattened or dropped. Fortunately JSON.parse() and JSON.stringify() each accept a hook function that lets you convert values on the way in and on the way out, and objects can define their own toJSON() method.

This lesson covers all three tools and finishes with two pitfalls that catch almost everyone: circular references and the "copy through JSON" trick.

flowchart LR
    A["JS value<br/>Date, Map, BigInt"] -- "toJSON() then replacer" --> B["JSON text<br/>strings, numbers, objects"]
    B -- "reviver" --> C["JS value again<br/>Date, Map, BigInt"]

Hooks sit at both ends of the round trip: the replacer and toJSON when writing, the reviver when reading.

Revivers: transform while parsing

The second argument of JSON.parse() is a reviver, a function called for every value in the parsed result. It receives the key and the value and returns what to store instead.

Revivers run bottom-up: the deepest values are visited first and the whole document last, with an empty string as its key. Returning undefined deletes that property.

JS Reviving dates while parsing

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Matching values by their shape (as the regular expression does here) can wrongly convert a string that merely looks like a date. When you know the field names, prefer matching by key:

JavaScript
JSON.parse(text, (key, value) => (key === "when" || key === "due" ? new Date(value) : value));

Replacers: transform while stringifying

The second argument of JSON.stringify() can be a function that is called for every property and returns the value to write. Return undefined to leave a property out. Inside the function, this is the object that holds the key, and the very first call has an empty key for the whole value.

JS A replacer that hides and converts values

Press Run (or Ctrl + Enter) to see the console output here.

No output.

A subtle gotcha: by the time the replacer sees a value, toJSON() has already been applied. A Date therefore arrives in your replacer as a string, not as a Date. If you need the original, read it from the holder with this[key].

JavaScript
JSON.stringify({ when: new Date(0) }, function (key, value) {
  console.log(typeof value, this[key] instanceof Date);   // "string", true
  return value;
});

Use an ordinary function, not an arrow function, when you need this.

toJSON: let an object describe itself

If an object has a method called toJSON(), JSON.stringify calls it and serializes the return value instead of the object. This is how Date writes itself as an ISO string, and you can add the same to your own classes.

JS Giving a class a toJSON method

Press Run (or Ctrl + Enter) to see the console output here.

No output.

toJSON is the right place for rules that belong to the type itself ("a Money value always serializes like this"). A replacer is better for rules that belong to one call ("this export hides passwords").

Map, Set and BigInt

Three built-in types need special handling.

  • Map and Set serialize as {}. Convert them to arrays or plain objects first ([...map], Object.fromEntries(map), [...set]).
  • BigInt throws a TypeError. Write it as a string (or number, if it is small), and convert it back on the way in.

A matching replacer and reviver pair keeps the round trip lossless. A common technique is to wrap such values in a small tagged object:

JS Round-tripping Map, Set and BigInt

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Notice that the reviver sees the inner objects before the outer ones (bottom-up), so by the time a wrapper object is reached its content is already plain data. The tagged shape is a convention you invent and document; the receiving side must know it, so use it between your own front end and back end, not in a public API for others.

The JSON.stringify of 9007199254740993n would throw without the replacer, and sending the digits as a number would have lost precision when the other side parsed them as a float. A string is the safe carrier for large integers.

Circular references

If an object contains itself, directly or through other objects, JSON.stringify throws a TypeError ("Converting circular structure to JSON"). It happens easily with parent and child links or with DOM nodes.

flowchart LR
    P["parent"] -- "children[0]" --> C["child"]
    C -- "parent" --> P

A cycle: the parent holds the child and the child points back to the parent, so serialization would never end.

The fix is to leave out one direction of the link, or to give the object a toJSON that does. A replacer can break cycles by remembering what it has already seen:

JS Breaking a circular reference

Press Run (or Ctrl + Enter) to see the console output here.

No output.

This simple helper marks any repeated object, not only true cycles, so an object that appears twice in a tree without any cycle is also replaced the second time. It is fine for logging; for real data, restructure it (store ids instead of references).

Deep copy pitfalls

JSON.parse(JSON.stringify(value)) is a famous shortcut for deep-copying. It works for plain objects, arrays, strings, numbers, booleans and null, and breaks quietly for everything else.

JS Copy through JSON versus structuredClone

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Prefer structuredClone() for in-memory copies: it keeps dates, maps, sets and cycles, and it throws a clear error on values it cannot copy (such as functions) instead of silently dropping them. Use the JSON approach only when you specifically want to normalize data into its JSON form.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In what order does a JSON.parse reviver visit values?

    The reviver walks the structure depth-first and visits the root last, with an empty string as its key.
  2. 2. What happens to a Date value before your replacer function sees it?

    toJSON runs first, so the replacer receives the string. Use this[key] inside a regular function to get the original Date.
  3. 3. What does JSON.stringify(new Map([['a', 1]])) return?

    A Map has no own enumerable properties, so it serializes as an empty object. Convert it to an array or object yourself.
  4. 4. Why is JSON.parse(JSON.stringify(x)) a poor general deep copy?

    JSON cannot represent those values, so they are dropped or flattened. structuredClone handles most of them properly.
  5. 5. What does an object's toJSON method control?

    JSON.stringify calls toJSON when it exists and serializes the returned value instead of the object itself.

Summary

  • A reviver passed to JSON.parse transforms values bottom-up; return undefined to delete a property.
  • A replacer function passed to JSON.stringify transforms or omits values; the original is available as this[key].
  • toJSON() lets a type control how it is serialized; Date already has one.
  • Map, Set and BigInt need conversion: Map and Set become {}, BigInt throws. Tagged objects with a matching reviver give a lossless round trip.
  • Circular references throw a TypeError; break the cycle with ids, toJSON or a replacer.
  • Prefer structuredClone() over JSON.parse(JSON.stringify(x)) for deep copies.

Next: Working with Nested JSON โ€” navigating, mapping and grouping real API data.