← 中文资源

简体中文版本

toJSON 决定 JSON.stringify 的输出形状

toJSON 是 JSON.stringify 序列化自定义类型的钩子,Date 正是用它输出 ISO 字符串;解析回来只是普通对象,序列化是单向契约。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

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"}

实现说明

除了类 Money,文件里再无其他定义。 顶层就这几处状态:invoice、restored。

常见问题

运行前要先安装什么?

什么都不用额外装——运行时自带了代码所需的一切。 跨调用保留的状态放在这些顶层绑定里:invoice、restored。

核心语句

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

代码示例

// 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));