toJSON contract

Allen Wirfs-Brock Allen.Wirfs-Brock at
Tue Sep 1 09:11:13 PDT 2009

Regarding toJSON results:

>-----Original Message-----
>From: es-discuss-bounces at [mailto:es-discuss-
>bounces at] On Behalf Of Hallvord R. M. Steen
>Sent: Tuesday, September 01, 2009 7:39 AM
>Subject: Re: more JSON spec questions...
>> integration/004.js makes Math.toJSON returns a stringified object
>> instead of the new object itself,
>If that's wrong, I've misunderstood how toJSON() is supposed to work
>(thought it was meant to return a *string* representation of the
>I see from the algorithm that the output of the toJSON() call goes
>the quote operation if it is a string and the JA/JO serializations if
>array or object, but the spec does not really cover this issue in prose
>anywhere?! It's a bit late for such feedback but the functionality of a
>custom toJSON() method seems really underdefined.

I believe that the original intent from json2.js was that toJSON functions were supposed to return primitive values.  However, the formulation of the Str algorithm in 15.12.3 pretty clearly allows for toJSON functions that return objects. From the algorithms, we can determine that the rules of toJSON are:
*Returns a replacement for its this value that JSON.stringify will output
*The replacement value may be either a primitive value or an Object.
*Normal stringify processing is applied to the replacement value including applying a replacer function or whitelist to it. However, if a replacement value has a toJSON method it is not called. Hence toJSON replacement only goes one level deep.

Doug, this suggests to me that the last two steps of Date.prototype.toJSON ( that throw a TypeError if the result is not a primitive value are unnecessary.  Should I get rid of them.


More information about the es-discuss mailing list