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

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

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


当前回答

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部分,数据类型)。

其他回答

JSON5允许使用标准的Javascript符号来表示正无穷大和负无穷大、NaN以及许多其他在JSON中被省略的有效ECMAScript(后面的逗号等)。

https://json5.org/

这使得JSON成为一种更有用的格式。

然而,无论是使用JSON还是JSON5:出于安全原因,总是总是解析——不要计算!!

字符串“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"}"

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部分,数据类型)。

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

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

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

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