Search code examples
javascriptjsonmomentjsstringify

How does JSON.stringify automagically convert moment objects to iso strings?


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.com/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

Solution

  • From MDN:

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

    From moment:

    proto.toJSON         = toISOString;