javascriptdateserialization

serialize and deserialize dates


I want to serialize and deserialize dates using a custom format. For that, I'm trying to intercept the date during JSON.stringify() using a custom receiver

function serialize(data) {
   if (data === undefined) {
      return JSON.stringify('__undef__')
   }

   if (data instanceof Date) {
      return JSON.stringify({ _t: 'dt', v: data.getTime() })
   }

   return JSON.stringify(data, (_, value) => {
      if (value === undefined) {
         return '__undef__'
      }

      if (value instanceof Date) {
         return { _t: 'dt', v: value.getTime() }
      }

      return value
   })
}

console.log(serialize(new Date(2024, 7, 4))); // {"_t":"dt","v":1722729600000}
console.log(serialize([undefined, new Date(2024, 7, 4)])); // ["__undef__","2024-08-04T00:00:00.000Z"]

Seems like the receiver is not intercepting the date format before serialization.

What am I doing wrong?


Solution

  • The value passed to the replacer function is actually the result of calling the Date.prototype.toJSON function so you cannot compare it directly with the instance of date. Instead if you compare the parent object property via this[key] with the instance of Date it should work.

    function replacer(key, value) {
      if (value === undefined) return "__undef__";
      if (this[key] instanceof Date) return { _t: 'dt', v: this[key].getTime() };
      return value;
    }
    
    console.log(JSON.stringify(undefined, replacer));
    console.log(JSON.stringify(new Date(), replacer));
    console.log(JSON.stringify([undefined, new Date()], replacer));