JSON decoding

Bob Ippolito bob at redivi.com
Fri Oct 20 13:11:03 PDT 2006

On 10/20/06, Brendan Eich <brendan at mozilla.org> wrote:
> On Oct 20, 2006, at 3:51 PM, Bob Ippolito wrote:
> > On 10/20/06, Brendan Eich <brendan at mozilla.org> wrote:
> >> On Oct 20, 2006, at 3:36 PM, Erik Arvidsson wrote:
> >>
> >> > If Date is serialized as an ISO strings the process of encoding and
> >> > decoding loses information. If Dates are added to JSON then they
> >> > should be encoded using new Date(ms). However Dates are not
> >> supported
> >> > in JSON today and removing them from JS2 seems OK.
> >>
> >> ES4 also standardizes Date.parse to accept the same ISO 8601 date
> >> strings, so I don't believe any information is lost.
> >
> > Even if there wasn't, you can always turn strings into dates the hard
> > way as MochiKit does...
> Sure.  That was more an FYI (ECMA-262 left Date.parse unspecified, a
> botch that requires browsers to reverse engineer IE JScript's
> Date.parse implementation).
> > The important part is that the metadata that it is a date is lost,
> > even if there's an easy way to make dates from strings. You have to
> > know which strings should be treated as dates.
> You're right, but JSON does not provide any way to distinguish this
> case (preserve the bit of metadata you cite).
> >> You're right that this automatic encoding of Date objects as ISO
> >> strings does not result, when decoding, in Date objects again.
> >> Fixing that would require a pass over the decoded structure, or a use
> >> of the optional object hook on the enclosing object.  Is this a
> >> problem?
> >
> > The object hook would be no good here because it would have to be able
> > to find ISO strings by key (or regexing all string values looking for
> > dates.. bleh).
> The context would have to determine what's a date and what is not.
> Yeah, it's poor, but without extending JSON, what can be done?

The encoder should have an object hook the same way the decoder does.
Throw away the filter.

You'd have an encoder hook that knows how to turn a Date object into
some specific object representation, and a decoder hook that does the
inverse. Then you could use the JSON encoder to encode whatever you
wanted into a valid JSON document however it needed to be laid out.

Filtering functionality can be implemented if necessary by writing an
encoder hook that inspects the object. If it needs to remove some
key:value pairs, then it would create a new object that is missing the
keys that should be filtered.


More information about the Es4-discuss mailing list