JSON 整数: 大小限制

是否在任何地方指定了 JSON 整数的大小?我猜测它们仅限于普通(32位)整型数,但是我找不到任何写下来的地方。我需要对 Java 中的 long 标识符进行编码,所以我假定我需要将这些标识符作为字符串存储在 JSON 中,以免出现溢出的风险。

72455 次浏览

A JSON number is not limited by the spec.

JSON number grammar

Since JSON is an abstract format that is not exclusively targeted at JavaScript, the actual target environment determines the boundaries of what can be interpreted.

It's also worth noting that there are no "JSON Integers", they are a sub-set of the "Number" datatype.

I just did the following empirical test using Chrome (v.23 on Mac) Console:

> var j = JSON.parse("[999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999]")
undefined


> j[0]
1e+228

If JSON is passed through HTTP then the number will be converted in String from Java in any case and then the issue could be only in Javascript.

From ECMAScript Language Specification 4.3.19:

4.3.19 Number value

primitive value corresponding to a double-precision 64-bit binary format IEEE 754 value

NOTE A Number value is a member of the Number type and is a direct representation of a number.

Which is what defined in wikipedia Double-precision floating-point format.

RFC 7159: The JavaScript Object Notation (JSON) Data Interchange Format

This specification allows implementations to set limits on the range and precision of numbers accepted. Since software that implements IEEE 754-2008 binary64 (double precision) numbers [IEEE754] is generally available and widely used, good interoperability can be achieved by implementations that expect no more precision or range than these provide, in the sense that implementations will approximate JSON numbers within the expected precision. A JSON number such as 1E400 or 3.141592653589793238462643383279 may indicate potential interoperability problems, since it suggests that the software that created it expects receiving software to have greater capabilities for numeric magnitude and precision than is widely available.