toJSON contract

Douglas Crockford douglas at
Tue Sep 1 09:24:48 PDT 2009

Allen Wirfs-Brock wrote:
> Regarding toJSON results:
> 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.

Yes, I think they can be reduced to

5.	Return result.

More information about the es-discuss mailing list