toJSON Controls What JSON.stringify Writes

A toJSON method decides what JSON.stringify writes for a custom type, the same hook Date uses to emit its ISO string; parsing back yields plain objects only.

JavascriptData Integrity

Code

javascriptsnippet
22 lines
// toJSON 决定自定义类型在 JSON.stringify 里写出的形状
class Money {
  constructor(cents, currency = 'USD') {
    this.cents = cents;
    this.currency = currency;
  }

  toJSON() {
    return (this.cents / 100).toFixed(2) + ' ' + this.currency;
  }
}

const invoice = { total: new Money(12345), due: new Date('2026-03-01T00:00:00Z') };
console.log('Money.toJSON  :', invoice.total.toJSON());
console.log('Date.toJSON   :', invoice.due.toJSON());

// stringify 对每个值调用 toJSON,而不是展开自有字段
console.log('stringified   :', JSON.stringify(invoice));

// 解析回来只是普通对象:toJSON 是单向的序列化契约
const restored = JSON.parse(JSON.stringify(invoice));
console.log('parsed back   :', typeof restored.total, JSON.stringify(restored));

Output

Captured from a sandboxed run of this snippet in the build pipeline.

Money.toJSON  : 123.45 USD
Date.toJSON   : 2026-03-01T00:00:00.000Z
stringified   : {"total":"123.45 USD","due":"2026-03-01T00:00:00.000Z"}
parsed back   : string {"total":"123.45 USD","due":"2026-03-01T00:00:00.000Z"}

Inside the snippet

toJSON Controls What JSON.stringify Writes reduces to the class Money.

Module-level bindings hold the data — invoice, restored — with no function scope in between.

Putting it to use

The demo output is labeled (Money.toJSON :, Date.toJSON :, stringified :), so every printed line maps back to its originating operation.

Core lines

return (this.cents / 100).toFixed(2) + ' ' + this.currency;
const restored = JSON.parse(JSON.stringify(invoice));

Interactive Tools for This Topic

FAQ

What has to be installed first?
Nothing — the runtime itself provides everything the code touches. Its state lives in module-level bindings: `invoice`, `restored`.