3

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
Catfish
  • 18,876
  • 54
  • 209
  • 353

2 Answers2

7

From MDN:

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

From moment:

proto.toJSON         = toISOString;
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
3

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().

Pointy
  • 405,095
  • 59
  • 585
  • 614