最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How does JSON.stringify automagically convert moment objects to iso strings? - Stack Overflow

programmeradmin1浏览0评论

I'm curious how libs like moment, automagically convert from objects to strings when JSON.stringify is called on that object.

Example test in moment: .js#L144-L146

Here's some example code that i'm curious how it works

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

I'm curious how libs like moment, automagically convert from objects to strings when JSON.stringify is called on that object.

Example test in moment: https://github./moment/moment/blob/3147fbc486209f0b479dc0b29672d4c2ef39cf43/src/test/moment/format.js#L144-L146

Here's some example code that i'm curious how it works

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
Share Improve this question asked Dec 13, 2019 at 21:25 CatfishCatfish 19.3k60 gold badges213 silver badges358 bronze badges 2
  • Pretty sure JSON.stringify casts all non-primitives as strings, so custom toString method is the likely answer. – Jared Smith Commented Dec 13, 2019 at 21:31
  • @JaredSmith no, it turns them into JSON :) – Pointy Commented Dec 13, 2019 at 21:31
Add a ment  | 

2 Answers 2

Reset to default 8

From MDN:

If the value has a toJSON() method, it's responsible to define what data will be serialized.

From moment:

proto.toJSON         = toISOString;

If an object has a .toJSON() method, JSON.stringify() will call that before attempting to do it's own thing with the object.

Date objects, and apparently Moment wrapper objects, have .toJSON() that calls .toISOString().

发布评论

评论列表(0)

  1. 暂无评论