Skip to content
Tutorials Center
My learning

Topics

JavaScript Reference ยท JSON, Errors and Reflection

The toJSON() method

Reference for the toJSON() method: how JSON.stringify() calls it, the key argument, how Date uses it, and how to serialize your own classes cleanly.

toJSON() is not a built-in method of every object. It is a convention: if a value has a method called toJSON, JSON.stringify() calls it and serializes the returned value instead of the object itself. Dates use this to become ISO strings, and you can add it to your own classes to control exactly what ends up in the JSON.

This keeps serialization logic next to the data it describes, and it works no matter how deeply the object is nested inside what you are stringifying.

JavaScript
class Point {
  constructor(x, y) { this.x = x; this.y = y; }
  toJSON() { return [this.x, this.y]; }
}
JSON.stringify(new Point(2, 3)); // "[2,3]"

Try it

JS Controlling a class's JSON

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

No output.

JS The key argument and a round trip

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

No output.

Syntax

JavaScript
value.toJSON(key)
Name Description
key A string. The property name under which the value is stored in its parent, an array index as a string for array elements, or "" for the top-level value.

Return value: any value that JSON.stringify() can then serialize. It is processed as usual, so it may itself contain further objects with their own toJSON() methods, or be undefined (which omits the property from an object).

Exceptions: none by itself. An exception thrown inside toJSON() propagates out of JSON.stringify().

Usage notes

  • Called by JSON.stringify() only. JSON.parse() never calls it; to restore instances, use a reviver or a static factory.
  • Called before the replacer. The replacer function receives the value returned by toJSON().
  • this is the value. Use a regular method (or a function expression), not an arrow function, if you need this.
  • Look-up uses the normal prototype chain, so subclasses inherit it, and a property that holds a function named toJSON also counts.
  • Hide secrets here. Returning a copy without sensitive fields is a clear way to avoid leaking them into logs or API responses.
  • A tag helps round trips. Include a type field so the reviver can tell which objects to rebuild.
  • BigInt. BigInt.prototype.toJSON does not exist; add one (returning a string) if you must serialize bigints, but this changes a shared built-in.
  • Return plain data. Returning this from toJSON() is allowed, but returning an object that contains a cycle still fails.

Browser support

toJSON() is part of JSON.stringify() in every browser and runtime, including very old ones.