Back to results for “Classes & Class Syntax”
JavaScript › JSON & Data Serialization

How does defining a toJSON() method on a class customize its JSON.stringify() output?

Advanced

Answer

If an object has a toJSON() method, JSON.stringify() calls it and serializes ITS return value instead of the object's own properties directly — a clean way to control exactly how a custom class is represented in JSON without a manual replacer.
class Money {
  constructor(cents) { this.cents = cents; }
  toJSON() { return (this.cents / 100).toFixed(2); }
}
JSON.stringify({ price: new Money(1999) }); // '{"price":"19.99"}'
Real-world example Making a Money or Temperature value object serialize as a simple display-friendly value instead of its internal representation.

Common follow-ups: Does Date's built-in toISOString-based JSON output work the same way, via its own toJSON() method?