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
2 Answers
Reset to default 8From 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()
.