至少在 Firefox 中,您可以将 Date 对象字符串化:
>>> JSON.stringify({'now': new Date()})
'{"now":"2012-04-23T18:44:05.600Z"}'
这是有效的,因为(在 Firefox 中)Date
包含一个 toJSON
方法,该方法由其 JSON 序列化程序使用。但是,这不是 JSON 标准的一部分,所以我想知道为什么存在这种方法,或者为什么内置 JSON 序列化程序会检查这种方法。由于它不是标准化的,如果内置序列化器理解它,你就不能安全地使用它,否则就使用自定义序列化器(例如 json2.js )
最佳答案
之所以可行,是因为它在规范中不是很明确。开始时,您需要深入了解 15.12.3 部分 在抽象操作 Str 的描述中,它用于将值转换为字符串表示形式。本质上,如果输入是一个对象,规范说要检查是否存在名为 toJSON
的可调用值。 .将其视为 Java 或 C# 中的接口(interface)。
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 强>。
关于javascript - 为什么 JSON.stringify() 接受 Date 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10286385/