Glossary / toJSON

toJSON

toJSON is a method that JSON.stringify calls to obtain a value for serialization. It lets objects define a wire representation; built-in Date uses it to produce an ISO-formatted string. A toJSON hook is a serialization policy, not a clone, validator, or guarantee that the resulting representation can reconstruct the original object.

Invocation and interaction with replacers

const point = {
  x: 3,
  y: 4,
  toJSON(key) { return { coordinates: [this.x, this.y], key }; },
};
JSON.stringify(point); // serializes the object returned by toJSON

The key argument is empty for a top-level value, the property name for an object member, and an index string for an array element. The value returned by toJSON is then processed by the replacer, if one is supplied. BigInt is a special case where stringify attempts to call toJSON; absent custom handling, it throws.

A hook may omit confidential fields, but that is not a security boundary if another serialization path exists. It can also leak secrets, produce cycles, mutate state, or make output dependent on context. Keep it deterministic and document the representation. Avoid patching built-in prototypes globally; local adapters or replacers make serialization policy easier to review.

Interview questions

  1. When does JSON.stringify call toJSON? When serializing a value with that method, before ordinary serialization of the returned value.
  2. What does its key argument contain? Context such as empty top-level key, property name, or array index string.
  3. Does toJSON validate data? No; it chooses a serialized representation.
  4. How can it affect BigInt? A custom BigInt toJSON can supply a representation; otherwise serialization throws.

References