Sub topic 8
Controlling Serialization with toJSON
This chapter assumes you know how JSON.stringify handles basic values, how it treats unsupported values such as undefined and functions, and how a replacer function works. You should also be comfortable with JavaScript classes and the this keyword.
A replacer controls serialization from the outside, at the call site. toJSON puts that control inside the object. If a value has a toJSON method, JSON.stringify calls it and serializes whatever it returns instead of the original value. You have already seen this mechanism at work: Date objects come out as ISO strings because Date.prototype.toJSON exists.
The basic contract
Here is a class whose instances store money as integer cents but should appear in JSON as a decimal amount:
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"}}The contract has three parts:
JSON.stringifychecks each value it is about to serialize. If the value is an object (or a BigInt) and has a callabletoJSONproperty, own or inherited, the method is called withthisset to that value.- The return value takes the place of the original. Its type can be anything. Objects, arrays, strings, numbers, booleans,
null, andundefinedare all allowed. - The replacement is then serialized by the normal rules. Nested properties get the same
toJSONcheck.
Because class methods live on the prototype and are not enumerable, the toJSON method itself never appears in the output.
Where toJSON fits in the pipeline
For each property, JSON.stringify runs a fixed sequence. toJSON runs first. If you passed a replacer function, it runs second and receives whatever toJSON returned. After that, the result is serialized.
You can see the ordering directly:
const reading = {
temp: {
c: 21,
toJSON() {
return { celsius: this.c };
}
}
};
const out = JSON.stringify(reading, (key, value) => {
if (key === "temp") console.log("replacer saw:", value);
return value;
});
// replacer saw: { celsius: 21 }
console.log(out); // {"temp":{"celsius":21}}The replacer never sees the original { c: 21, toJSON } object. This matters when you combine the two. A replacer that checks value instanceof Money will never match, because by the time the replacer runs, the Money instance has already become a plain object.
The key argument
toJSON receives one argument: the key under which the value is being serialized. For object properties that is the property name. For array elements it is the index as a string. For the top-level value it is the empty string.
const tagged = {
toJSON(key) {
return key === "" ? "root" : `field:${key}`;
}
};
console.log(JSON.stringify(tagged));
// "root"
console.log(JSON.stringify({ a: tagged, list: [tagged] }));
// {"a":"field:a","list":["field:0"]}You will rarely need this argument. It exists mostly so that toJSON can follow the same signature as a replacer. Making output depend on the key also makes it depend on where an object sits in the tree, and that tends to surprise readers of the data.
Common uses
Exposing private state
Private class fields (#field) are not own enumerable properties, so JSON.stringify ignores them. Without toJSON, a class that keeps all its state private serializes as an empty object.
class Counter {
#count = 0;
increment() {
this.#count += 1;
return this;
}
}
class SerializableCounter extends Counter {
#label;
constructor(label) {
super();
this.#label = label;
}
toJSON() {
return { label: this.#label, count: this.count };
}
get count() {
return JSON.parse(JSON.stringify(new Counter())) && this.#countValue();
}
#countValue() {
return this.#n;
}
#n = 0;
increment() {
this.#n += 1;
return this;
}
}That example is more convoluted than it needs to be, so here is the direct version:
class Counter {
#count = 0;
increment() {
this.#count += 1;
return this;
}
toJSON() {
return { count: this.#count };
}
}
class Hidden {
#count = 3;
}
console.log(JSON.stringify(new Hidden())); // {}
console.log(JSON.stringify(new Counter().increment().increment())); // {"count":2}Hiding sensitive or internal fields
toJSON is a good place to make sure a field never leaves the object, regardless of who calls JSON.stringify or which replacer they pass:
class User {
constructor(name, passwordHash) {
this.name = name;
this.passwordHash = passwordHash;
this.createdAt = new Date(0);
}
toJSON() {
const { passwordHash, ...safe } = this;
return safe;
}
}
console.log(JSON.stringify(new User("ada", "x9f...")));
// {"name":"ada","createdAt":"1970-01-01T00:00:00.000Z"}The returned object still holds a Date in createdAt. The serializer recurses into it and calls Date.prototype.toJSON, which produces the ISO string.
Giving collections a useful shape
Map and Set have no toJSON, so they serialize as {}. A subclass can fix that:
class JsonMap extends Map {
toJSON() {
return Object.fromEntries(this);
}
}
class JsonSet extends Set {
toJSON() {
return [...this];
}
}
console.log(JSON.stringify({
scores: new JsonMap([["ada", 3], ["alan", 5]]),
tags: new JsonSet(["math", "code", "math"])
}));
// {"scores":{"ada":3,"alan":5},"tags":["math","code"]}Object.fromEntries turns every key into a string, so a map keyed by numbers or objects loses information. If the keys aren't strings, return [...this] instead. That gives an array of [key, value] pairs, which can be passed straight back to new Map(...).
Adding a type tag for later revival
toJSON only works in one direction. JSON.parse knows nothing about it, so a parsed Money comes back as a plain object. If you plan to rebuild instances, include a marker in the output for a reviver to look for:
class Money {
constructor(cents, currency) {
this.cents = cents;
this.currency = currency;
}
toJSON() {
return { $type: "Money", cents: this.cents, currency: this.currency };
}
}
console.log(JSON.stringify([new Money(500, "USD")]));
// [{"$type":"Money","cents":500,"currency":"USD"}]The next chapter shows the reviver side of this pattern. Keep the tagged shape lossless. Here cents is kept as an integer instead of being converted to a decimal amount, so the reviver has no rounding to undo.
Built-in toJSON implementations
| Type | Has toJSON? | Output |
|---|---|---|
| `Date` (valid) | Yes | ISO 8601 string from `toISOString()` |
| `Date` (invalid) | Yes | `null` |
| `URL` | Yes | The `href` string |
| `Map`, `Set` | No | `{}` |
| `RegExp`, `Error` | No | `{}` (no own enumerable properties) |
| `BigInt` | No | Throws `TypeError` |
The invalid-date row catches people out. You might expect an error, but you get null:
console.log(JSON.stringify({ due: new Date("not a date") }));
// {"due":null}If null is not an acceptable value in your data, validate dates before serializing.
Failure modes
Infinite recursion
Calling JSON.stringify(this) inside toJSON calls toJSON again, and that never ends:
const bad = {
a: 1,
toJSON() {
return JSON.stringify(this);
}
};
try {
JSON.stringify(bad);
} catch (err) {
console.log(err instanceof RangeError); // true (maximum call stack size exceeded)
}The same thing happens if toJSON returns this together with a structure that leads back into it. Return a new plain object or a primitive instead.
Double-encoded strings
toJSON should return a value to be serialized. It should not return JSON text. If you return a string, that string is quoted and escaped like any other string:
const wrong = {
toJSON() {
return JSON.stringify({ x: 1 });
}
};
console.log(JSON.stringify({ p: wrong }));
// {"p":"{\"x\":1}"}The consumer now has to parse twice. Return { x: 1 } instead.
Arrow functions and `this`
toJSON relies on this being the object. An arrow function assigned as a property captures the surrounding this, so it reads the wrong values:
const temp = {
c: 21,
toJSON: () => ({ celsius: this?.c })
};
console.log(JSON.stringify(temp));
// {} in a module or strict context, because this.c is undefined and the key is omittedUse method syntax (toJSON() { ... }) or a regular function.
Returning undefined
When toJSON returns undefined, the same rules apply as for a literal undefined. The property is omitted from objects, becomes null in arrays, and at the top level JSON.stringify returns undefined instead of a string. This is a legitimate way to make a value "invisible" to JSON, but code that expects JSON.stringify to always return a string will break.
Throwing inside toJSON
Any exception thrown in toJSON propagates out of JSON.stringify and aborts the whole call. No partial output is produced. If toJSON reads lazily loaded or possibly missing state, guard those reads.
toJSON or a replacer?
| Question | toJSON | Replacer |
|---|---|---|
| Who decides the shape? | The class author | The caller |
| Applies to every stringify call? | Yes | Only calls that pass it |
| Can see the original instance? | Yes | No, only the toJSON result |
| Works on types you don't own? | Only by patching prototypes | Yes |
| Good for | Canonical wire format, hiding secrets | Per-endpoint filtering, logging, redaction |
A practical rule: put the canonical representation of a type in toJSON, and use replacers for context-specific changes such as dropping fields for one API response or making debug output shorter.
Exercise
A class Point has a toJSON method returning { x: this.x, y: this.y }. You call JSON.stringify(new Point(1, 2), (k, v) => v instanceof Point ? "POINT" : v). What is printed, and why?
Show answer
It prints {"x":1,"y":2}. toJSON runs before the replacer, so the replacer receives the plain object { x: 1, y: 2 } rather than the Point instance. The instanceof check fails and the value passes through unchanged.
Exercise
Write a class Temperature that stores kelvin in a private field #k and serializes as {"celsius": <number>}. What does JSON.stringify([new Temperature(300)]) print?
Show answer
class Temperature { #k; constructor(k) { this.#k = k; } toJSON() { return { celsius: this.#k - 273.15 }; } } — the call prints [{"celsius":26.850000000000023}]. Floating-point subtraction gives that long decimal. Rounding inside toJSON, for example Math.round((this.#k - 273.15) * 100) / 100, gives [{"celsius":26.85}].
Exercise
Given const d = { when: new Date("2024-02-30T00:00:00Z") }, what does JSON.stringify(d) return, and what about { when: new Date("garbage") }?
Show answer
The first returns {"when":"2024-03-01T00:00:00.000Z"}, because the Date constructor rolls February 30 over to March 1 and the result is a valid date. The second returns {"when":null}, because Date.prototype.toJSON returns null for an invalid date instead of throwing.