【问题标题】:How does JSON.stringify automagically convert moment objects to iso strings?JSON.stringify 如何自动将 moment 对象转换为 iso 字符串?
【发布时间】:2020-04-07 08:16:48
【问题描述】:

我很好奇像 moment 这样的库是如何在对该对象调用 JSON.stringify 时自动从对象转换为字符串的。

即时示例测试:https://github.com/moment/moment/blob/3147fbc486209f0b479dc0b29672d4c2ef39cf43/src/test/moment/format.js#L144-L146

这是一些示例代码,我很好奇它是如何工作的

const moment = require('moment');
const duration = moment.duration(1374);
console.log('duration = ', duration); // Prints a duration object
console.log('JSON.stringify(duration) = ', JSON.stringify(duration)); // Prints a string such as `P0D1T0H3` <-- Note: Not exact value, just similar format

【问题讨论】:

  • 相当肯定 JSON.stringify 将所有非原始类型转换为字符串,因此自定义 toString 方法可能是答案。
  • @JaredSmith 不,它会将它们转换为 JSON :)

标签: javascript json momentjs stringify


【解决方案1】:

来自MDN:

如果该值有一个 toJSON() 方法,它负责定义哪些数据将被序列化。

来自moment:

proto.toJSON         = toISOString;

【讨论】:

    【解决方案2】:

    如果一个对象有一个.toJSON() 方法,JSON.stringify() 将在尝试对该对象做自己的事情之前调用它。

    日期对象,显然是 Moment 包装器对象,具有调用 .toISOString() 的 .toJSON()。

    【讨论】:

      猜你喜欢
      • 2020-04-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多