Sub topic 8
Controlling Serialization with toJSON
This chapter assumes you know how JSON.stringify handles plain objects and unsupported values, and that you have seen a replacer function. It shows how an object can decide for itself what its JSON looks like.
What toJSON Does
Before JSON.stringify serializes a value, it checks whether that value has a method named toJSON. If it does, stringify calls the method and serializes the return value in place of the original object. You already rely on this whenever you stringify a Date, because Date.prototype.toJSON returns an ISO string.
This lets a class own its wire format. Callers don't need to pass a replacer.
class Money {
constructor(cents, currency) {
this.cents = cents;
this.currency = currency;
}
toJSON() {
return { amount: this.cents / 100, currency: this.currency };
}
}
console.log(JSON.stringify({ price: new Money(1999, "EUR") }));
// {"price":{"amount":19.99,"currency":"EUR"}}Stringify works recursively, so a Money nested anywhere in a structure, at any depth or inside an array, gets the same treatment.
Hiding Internal Fields
A common use is keeping private or derived state out of the output:
class User {
constructor(name, passwordHash) {
this.name = name;
this.passwordHash = passwordHash;
this.cache = new Map();
}
toJSON() {
return { name: this.name };
}
}
console.log(JSON.stringify([new User("ada", "x9f...")]));
// [{"name":"ada"}]Without toJSON, passwordHash would leak into the output, and cache would serialize as a useless {}.
The key Argument
Stringify passes toJSON the key under which the value appears. The key is "" at the root, the property name inside an object, and the index as a string inside an array.
const probe = {
toJSON(key) {
return key === "" ? "root" : `in ${key}`;
}
};
console.log(JSON.stringify(probe)); // "root"
console.log(JSON.stringify({ a: probe })); // {"a":"in a"}
console.log(JSON.stringify([probe])); // ["in 0"]Most toJSON methods ignore the key. It is there for cases where context should change the output.
Order of Operations: toJSON Runs Before the Replacer
For each value, stringify first calls toJSON, then passes the result to the replacer. This explains a frequent surprise: a replacer never sees a Date as its value, only the string it became. The original is still available as this[key], but only if the replacer is a regular function, because arrow functions don't get their own this.
const data = { at: new Date(0) };
JSON.stringify(data, function (key, value) {
if (key === "at") {
console.log(typeof value); // "string"
console.log(this[key] instanceof Date); // true
}
return value;
});Common Mistakes
| Mistake | Result | Fix |
|---|---|---|
| Returning `JSON.stringify(...)` from `toJSON` | Double-encoded string such as `"{\"a\":1}"` | Return a plain value or object, not a string of JSON |
| Returning `undefined` by accident | The property disappears from the output | Always return a value, unless dropping it is what you want |
| Expecting `JSON.parse` to call something in reverse | You get back plain objects, not class instances | Rebuild instances with a reviver (next chapter) |
| Using an arrow-function replacer to inspect originals | `this` doesn't point to the holder object | Use a `function` replacer |
Exercises
Exercise
What does JSON.stringify({ when: { toJSON() { return JSON.stringify({ y: 2024 }); } } }) print, and how would you fix it so the output is {"when":{"y":2024}}?
Show answer
It prints {"when":"{\"y\":2024}"} because toJSON returned a string, and stringify encodes that string as a JSON string value. Fix it by returning the object itself: toJSON() { return { y: 2024 }; }.
Exercise
A replacer (key, value) => value instanceof Date ? value.getTime() : value never converts Dates to timestamps. Why, and how do you fix it?
Show answer
Date's toJSON runs before the replacer, so value is already an ISO string. Use a regular function and check the original: function (key, value) { return this[key] instanceof Date ? this[key].getTime() : value; }.