为什么JSON.stringify()接受Date对象? [英] Why does JSON.stringify() accept Date objects?

查看:466
本文介绍了为什么JSON.stringify()接受Date对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

至少在Firefox中,您可以对Date对象进行字符串化:

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

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

这是因为(在Firefox中) Date 包含一个 toJSON 它的JSON序列化器使用的方法。但是,这不是JSON标准的一部分,所以我不知道为什么这个方法存在,或者为什么内置的JSON序列化程序检查这样的方法。由于它不是标准化的,所以无论如何首先测试内置的串行化程序是否理解它,否则使用自定义的(如 json2.js

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)

推荐答案

这是因为它被指定为不太清楚在规范内。首先,您需要深入了解 15.12.3 部分用于将值转换为字符串表示形式的抽象操作 Str 的描述。本质上,如果输入是一个对象,规范说要检查名为 toJSON 的可调用值的存在。想像这样一个接口在Java或C#。

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. 

最后,日期对象在 中定义的 toJSON href =http://es5.github.io/#x15.9.5.44 =nofollow> 15.9.5.44

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

这篇关于为什么JSON.stringify()接受Date对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆