JSON 序列化是否具有确定性



我正在使用一个以我意想不到的方式序列化 JSON 的应用程序。JSON 序列化是否具有确定性?在 Chrome 控制台中,我看到

> JSON.stringify(3)
"3"

但是此应用程序将数字 3 序列化为 "3.0" .

根据 JSON 规范 ECMA-404 和 RFC 8259,两者都显然是合法的,序列化"30.0E-01"也是如此。

JSON 标准中是否有任何内容指定了应该生成什么"规范"序列化?我什么也找不到。

好吧,一个特定的序列化程序可能会产生确定性的输出。但是没有标准的规范格式(至少被广泛使用,有这个互联网草案 - 但它从未成为RFC,而且远非如此(。

即使某处有一个"标准",它也没有被广泛使用,所以你不能指望JSON文档来维护它。

RFC 8259 说(部分(:

8.3.  String Comparison
   Software implementations are typically required to test names of
   object members for equality.  Implementations that transform the
   textual representation into sequences of Unicode code units and then
   perform the comparison numerically, code unit by code unit, are
   interoperable in the sense that implementations will agree in all
   cases on equality or inequality of two strings.  For example,
   implementations that compare strings with escaped characters
   unconverted may incorrectly find that "a\b" and "au005Cb" are not
   equal.
9.  Parsers
   A JSON parser transforms a JSON text into another representation.  A
   JSON parser MUST accept all texts that conform to the JSON grammar.
   A JSON parser MAY accept non-JSON forms or extensions.
   An implementation may set limits on the size of texts that it
   accepts.  An implementation may set limits on the maximum depth of
   nesting.  An implementation may set limits on the range and precision
   of numbers.  An implementation may set limits on the length and
   character contents of strings.
10.  Generators
   A JSON generator produces JSON text.  The resulting text MUST
   strictly conform to the JSON grammar.

这也意味着这些表示"a\b""au005Cb"同样有效;听起来好像没有有利的表示,只要满足所需的语法,一切都很好。

最新更新