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.
Code
// 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
CSV to JSON ConverterConvert comma-separated values into a JSON array of objects using the first row as field names, with support for quoted and escaped fields.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON Diff ViewerCompare two JSON documents and list every added, removed, and changed path in a structural diff, with clear before and after values.
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`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.