Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 879
Catfish Avatar asked Feb 16 '26 15:02

Catfish


1 Answers

From MDN:

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

From moment:

proto.toJSON         = toISOString;
like image 96
Quentin Avatar answered Feb 19 '26 06:02

Quentin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!