JSON.stringify and Date serialization issues

# Erik Arvidsson (17 years ago)

The issue with representing a Date as a string in JSON has been discussed before and the resolution was that stringify a Date object to the ISO date string was considered not desirable. However, in the latest proposed spec for ES3.1 this resolution seems to have been overlooked.

The problem is that if Date is serialized as a string then there is no longer a way to distinguish a string from a date object. It is therefore better not to have any special handling of Date. Even with the currently proposed spec for JSON one would on first glance believe that it would be possible to use the replacer argument to handle Dates in a way that might allow them to be parsed again without loosing information but the algorithm states that toJSON is called on the object before it is passed to the replacer function.

I can see 2 possible ways to resolve this.

  1. Drop toJSON on Date.prototype.
  2. Change how the replacer is called and pass it both the key, non-json-value and the json value. This would allow the user to detect a Date object and return whatever he/she wants.

-- erik

# Erik Arvidsson (17 years ago)

+es4-discuss

On Tue, Aug 12, 2008 at 10:22, Douglas Crockford <douglas at crockford.com> wrote:

There are currently three effective ways to change the default. That is enough. The replacer is able to choose between the original value and the toJSON candidate.

Changing Date.prototype.toJSON is not acceptable since it might break other scripts on the page.

What are the other 2 ways?