至少在 Firefox 中,您可以对 Date 对象进行字符串化:
>>> JSON.stringify({'now': new Date()})
'{"now":"2012-04-23T18:44:05.600Z"}'
这是有效的,因为(在 Firefox 中)Date
包含一个toJSON
其 JSON 序列化器使用的方法。但是,这不是 JSON 标准的一部分,因此我想知道为什么存在此方法,或者为什么内置 JSON 序列化程序会检查此类方法。由于它没有标准化,因此如果不首先测试内置序列化器是否理解它,您就无法安全地使用它,否则使用自定义序列化器(例如json2.js https://github.com/douglascrockford/JSON-js/blob/master/json2.js)
这是有效的,因为它是在规范中不太明确的内容中指定的。首先,您需要深入研究该部分15.12.3 http://es5.github.io/#x15.12.3在抽象操作的描述中Str它用于将值转换为字符串表示形式。本质上,如果输入是一个对象,则规范说要检查名为的可调用值是否存在toJSON
。可以将其视为 Java 或 C# 中的接口。
interface IAmJSON
{
string toJSON(string key);
}
这是规范中的确切文本。
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
节中定义15.9.5.44 http://es5.github.io/#x15.9.5.44.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)