Why does JSON.stringify() accept Date objects?

At least in Firefox, you can stringify a Date object:

>>> JSON.stringify({'now': new Date()})
'{"now":"2012-04-23T18:44:05.600Z"}'

This works because (in Firefox) Date contains a toJSON method which is used by its JSON serializer. However, this is not part of the JSON standard so I wonder why this method exists or rather why the builtin JSON serializer checks for such a method. Since it's not standardized you cannot safely use it anyway without first testing if the builtin serializer understands it and otherwise use a custom one (such as json2.js)


This works because it is specified in a not so clear matter within the specification. Starting out you need to dig in into section 15.12.3 in the description of the abstract operation Str which is used to convert values to a string representation. Essentially if the input is an object the specification says to check for the existance of a callable value named toJSON . Think of this like an interface in Java or C#.

interface IAmJSON 
{
    string toJSON(string key);
}

This is the exact text from the specification.

2.  If Type(value) is Object, then 
    a.  Let toJSON be the result of calling the [[Get]] internal method of  value with argument "toJSON". 
    b.  If IsCallable(toJSON) is true 
        i.  Let value be the result of calling the [[Call]] internal method of  toJSON passing value as the this value and with an argument list consisting of key. 

Finally, the date object has toJSON defined in section 15.9.5.44 .

链接地址: http://www.djcxy.com/p/8172.html

上一篇: PHP:文件下载不下载预期的文件

下一篇: 为什么JSON.stringify()接受Date对象?