知道为什么JSON省略了NaN和+/- Infinity吗?它将Javascript置于一种奇怪的情况中,如果对象包含NaN或+/-无穷大值,则对象将不可序列化。

看起来这已经是铁板一块了:参见RFC4627和ECMA-262(第24.5.2节,JSON。ECMA-262 pdf最后一次编辑第683页):

有限数字被字符串化,就像调用ToString(number)一样。NaN和Infinity,无论符号是什么,都表示为字符串null。


当前回答

原因在标准ECMA-404 JSON数据交换语法第1版的第2页说明

JSON is agnostic about numbers. In any programming language, there can be a variety of number types of various capacities and complements, fixed or floating, binary or decimal. That can make interchange between different programming languages difficult. JSON instead offers only the representation of numbers that humans use: a sequence of digits. All programming languages know how to make sense of digit sequences even if they disagree on internal representations. That is enough to allow interchange.

原因并不像许多人声称的那样,是由于NaN和Infinity ECMA脚本的表示。简单性是JSON的核心设计原则。

因为它非常简单,所以JSON语法不会发生任何变化。这为JSON(作为一种基本表示法)提供了极大的稳定性

其他回答

如果你像我一样无法控制序列化代码,你可以用null或任何其他值来处理NaN值,如下所示:

$.get("file.json", theCallback)
.fail(function(data) {
  theCallback(JSON.parse(data.responseText.replace(/NaN/g,'null'))); 
} );

本质上,当原始json解析器检测到无效令牌时,.fail将被调用。然后使用字符串replace替换无效的令牌。在我的情况下,它是一个例外的序列化器返回NaN值,所以这个方法是最好的方法。如果结果通常包含无效令牌,最好不要使用$。而不是手动检索JSON结果,并始终运行字符串替换。

如果您可以访问序列化代码,则可以将Infinity表示为1.0e+1024。指数太大,不能用双精度表示,反序列化时,它表示为无穷大。适用于webkit,不确定其他json解析器!

字符串“Infinity”、“-Infinity”和“NaN”都被强制转换为JS中的期望值。所以我认为在JSON中表示这些值的正确方法是字符串。

> +"Infinity"
Infinity

> +"-Infinity"
-Infinity

> +"NaN"
NaN

JSON太可惜了。Stringify默认情况下不这样做。但有一个办法:

> JSON.stringify({ x: Infinity }, function (k,v) { return v === Infinity ? "Infinity" : v; })
"{"x":"Infinity"}"

原因在标准ECMA-404 JSON数据交换语法第1版的第2页说明

JSON is agnostic about numbers. In any programming language, there can be a variety of number types of various capacities and complements, fixed or floating, binary or decimal. That can make interchange between different programming languages difficult. JSON instead offers only the representation of numbers that humans use: a sequence of digits. All programming languages know how to make sense of digit sequences even if they disagree on internal representations. That is enough to allow interchange.

原因并不像许多人声称的那样,是由于NaN和Infinity ECMA脚本的表示。简单性是JSON的核心设计原则。

因为它非常简单,所以JSON语法不会发生任何变化。这为JSON(作为一种基本表示法)提供了极大的稳定性

On the original question: I agree with user "cbare" in that this is an unfortunate omission in JSON. IEEE754 defines these as three special values of a floating point number. So JSON cannot fully represent IEEE754 floating point numbers. It is in fact even worse, since JSON as defined in ECMA262 5.1 does not even define whether its numbers are based on IEEE754. Since the design flow described for the stringify() function in ECMA262 does mention the three special IEEE values, one can suspect that the intention was in fact to support IEEE754 floating point numbers.

作为另一个与问题无关的数据点:XML数据类型xs:float和xs:double确实表明它们基于IEEE754浮点数,并且它们确实支持这三个特殊值的表示(参见W3C XSD 1.0第2部分,数据类型)。