20

以下是有效的 JSON 文本,还是它们的顶级值必须是数组或对象?

4.0
"Hello World"
true

过去的相关问题,例如最低有效 JSON 是多少?,并且这个简单的字符串是否被认为是有效的 JSON?得出的结论是他们不是。这是基于RFC-4627中对 JSON 格式的描述,其中指出:

2. JSON 语法

JSON 文本是一系列标记。标记集包括六个结构字符、字符串、数字和三个文字名称。

JSON 文本是一个序列化的对象或数组。

 JSON-text = object / array

这些是六个结构特征:

[...]

但是,RFC-4627 状态声明它“没有指定任何类型的 Internet 标准”。相反,JSON 的官方标准是最近发布的ECMA-404。与 RFC-4627 不同,ECMA-404 对有效 JSON 文本的描述不包括它是对象或数组的任何要求。例如,与上面引用最相似的部分缺少该要求:

4 JSON 文本

JSON 文本是由符合 JSON 值语法的 Unicode 代码点形成的标记序列。标记集包括六个结构标记、字符串、数字和三个文字名称标记。

六个结构标记:

[...]

鉴于这个新规范,编码的非数组非对象顶级值是否被视为有效的 JSON 文本?

4

1 回答 1

31

Douglas Crockford posted a comment on this Google+ post which helped me start to clarify things:

JSON is just a grammar, and the grammar includes numbers and strings. Uses of JSON must necessarily be more restrictive. RFC-4627 is one possible use, and was never intended to be the standard for JSON itself.

We cannot say that non-array non-object JSON texts are generally invalid, just that it is not valid to use them with internet media type application/json, per RFC-4627.

Representations of non-object non-array values are valid JSON texts per ECMA-404, which is the only currently published standard that might be identified as "the JSON specification".

However, it turns out that the IETF is likely to soon publish a replacement to RFC-4627 which will also be a specification of JSON. Its latest draft still includes the restriction on JSON texts, but also mentions that JSON has be specified in several places and that these specifications vary slightly. The draft specifically mentions that the definition of JSON in ECMA-262 (the ECMAScript/JavaScript specification) does not share the top-level value restriction.

Therefore, the question of whether non-object non-arrays are valid JSON texts must be disambiguated:

Is "hello" a valid JSON text as specified in RFC-4627 and its successor?

No.

Is "hello" a valid JSON text as specified by ECMA-404 and ECMA-262?

Yes.

于 2013-10-24T15:50:01.890 回答