关于标准:JSON语法是否允许对象中的重复键?

Does JSON syntax allow duplicate keys in an object?

这是有效的JSON吗?

1
2
3
4
{
   "a" :"x",
   "a" :"y"
}

http://jsonlint.com/表示同意。

http://www.json.org/没有提到被禁止。

但很明显这没什么意义,是吗?大多数实现可能使用哈希表,因此无论如何都要覆盖它。


的答案是:the short but is not建议。回答:长depends the valid在线呼叫你。P></

JSON数据交换格式(ECMA(404)不说duplicated names(anything about keys)。P></

不管一个人多,对象的位置(the JavaScript的JSON数据交换格式)()rfc7159)说:P></

The names within an object SHOULD be unique.

在understood as this should must be specified context在RFC 2119P></

SHOULD This word, or the adjective"RECOMMENDED", mean that there may
exist valid reasons in particular circumstances to ignore a particular
item, but the full implications must be understood and carefully
weighed before choosing a different course.

RFC 7159 explains为什么是好的独特的名称(键):P></

An object whose names are all unique is interoperable in the sense
that all software implementations receiving that object will agree on
the name-value mappings. When the names within an object are not
unique, the behavior of software that receives such an object is
unpredictable. Many implementations report the last name/value pair
only. Other implementations report an error or fail to parse the
object, and some implementations report all of the name/value pairs,
including duplicates.

JSON parsing libraries have been observed to differ as to whether
or not they make the ordering of object members visible to calling
software. Implementations whose behavior does not depend on member
ordering will be interoperable in the sense that they will not be
affected by these differences.

也有角,as the超时:在ECMA-262 ECMAScript的意见"?"语言规范,读取数:P></

In the case where there are duplicate name Strings within an object,
lexically preceding values for the same key shall be overwritten.

(in other words last-value-wins).

P></

想做出与Java字符串duplicated with the names(Douglas Crockford by the implementation of JSON结果在安创)例外:P></

1
2
org.json.JSONException: Duplicate key"status"  at
org.json.JSONObject.putOnce(JSONObject.java:1076)


从标准(P二):P></

It is expected that other standards will refer to this one, strictly adhering to the JSON text format, while
imposing restrictions on various encoding details. Such standards may require specific behaviours. JSON
itself specifies no behaviour.

唐氏在继续(P,标准规范。2)在JSON对象:for theP></

An object structure is represented as a pair of curly bracket tokens surrounding zero or more name/value pairs.
A name is a string. A single colon token follows each name, separating the name from the value. A single
comma token separates a value from a following name.

Diagram for JSON Object

它does not make any of钥匙被复制或拉提无效valid to the,我会根据安全规范是允许他们承担that means。P></

implementations that most of json图书馆复制钥匙does not do not accept the conflict with because of the first定额标准。P></

here are examples to the光子相关标准C + +库。当反序列化JSON对象在std::mapen into some keys to make会拒绝重复感。but when some反序列化JSON对象感会让它进入std::multimapto accept as normal复制钥匙。P></


指定JSON格式的文档有2个:

  • 网址:http://json.org/
  • https://tools.ietf.org/html/rfc7159
  • 接受的回答引自第一份文件。我认为第一份文件更清楚,但第二份包含更多细节。

    第二份文件说:

  • Objects

    An object structure is represented as a pair of curly brackets
    surrounding zero or more name/value pairs (or members). A name is a
    string. A single colon comes after each name, separating the name
    from the value. A single comma separates a value from a following
    name. The names within an object SHOULD be unique.

  • 因此,不禁止使用重复的名称,但不鼓励使用重复的名称。


    在处理同时接受XML和JSON的API时,我遇到了一个类似的问题,但没有记录它将如何处理您期望的JSON中的重复键。

    以下是示例JSON的有效XML表示形式:

    1
    2
    3
    4
    <object>
      x
      y
    </object>

    当它转换为JSON时,可以得到以下信息:

    1
    2
    3
    4
    5
    6
    7
    8
    {
     "object": {
       "a": [
         "x",
         "y"
        ]
      }
    }

    从一种处理可能称为重复键的语言到另一种的自然映射,可以作为这里潜在的最佳实践参考。

    希望能帮助别人!


    规格:JSON说this theP></

    An object is an unordered set of name/value pairs.

    here is the important part"无序"着欧洲唯一性:唯一的钥匙,因为你可以用is to推荐到特异性配对的钥匙。P></

    在反序列化JSON库之外,大多数将JSON对象映射到hash词典/键移调,哪里是独特的。什么发生在反序列化JSON对象,当你用复制的钥匙depends on the most cases图书馆:get an error,或者你,only the last value for each or will be taken into帐户复制的关键。P></

    在Python中,for example,{"a": 2}json.loads('{"a": 1,"a": 2}')归来。P></


    应该是唯一的并不意味着必须是唯一的。但是,如前所述,一些解析器将失败,而其他解析器将只使用解析的最后一个值。但是,如果规范被稍微清理一下以允许重复,那么我可以看到一种用法,您可以使用一个事件处理程序将JSON转换为HTML或其他格式……在这种情况下,解析JSON并创建其他文档格式是完全有效的……

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    [
     "div":
      {
       "p":"hello",
       "p":"universe"
      }
     "div":
      {
       "h1":"Heading 1",
       "p":"another paragraph"
      }
    ]

    例如,可以很容易地解析为HTML

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    <body>
     
      <p>
    hello
    </p>
      <p>
    universe
    </p>
     
     
      Heading 1
      <p>
    another paragraph
    </p>
     
    </body>

    我能看出问题背后的原因,但事实上……我不相信。


    用there are asking for different,回答:P></

    使用JSON对象的序列化(javascriptobjectnotation Maps to each词典元),个人财产安对象,知道在不同的defining entries property value for the same meaning"不。P></

    不管一个人多,the same question from a肉类过甚特异性用房:JSON API for samples写作测试,我想知道我们的意见how to add into the usability JSON文件没有打破。does not the JSON技术规格的意见,我想出的方法很简单:P></

    我们重复使用Keys to comment to samples JSON。实例:P></

    {
    "property1" :"value1", "REMARK" :"... prop1 controls ...",
    "property2" :"value2", "REMARK" :"... value2 raises an exception ...",
    }
    P></

    我们是使用JSON序列化the which have with"remark"这些问题不只是与我们的应用代码duplicates ignores this量小。P></

    即使不知道,there is on the meaning for duplicates应用层提供在美国,这些工作对我们valuable to add to the samples没有通过测试usability of the JSON。P></


    根据Internet工程任务组(IETF)发布的现行JSON标准RFC-7159,该标准规定"对象中的名称应该是唯一的"。然而,根据定义IETF文档中使用术语的RFC-2119,单词"应该"实际上意味着"…在特定情况下,忽略某一特定项目可能存在合理的理由,但在选择不同的课程之前,必须理解并仔细权衡其全部含义。"这本质上意味着,虽然建议使用唯一的键,但这不是必须的。我们可以在JSON对象中有重复的键,它仍然有效。

    从实际应用程序中,我已经看到当在JSON中发现重复的键时,考虑最后一个键的值。


    这是not the ECMA标准定义JSON。generally布尔扎克说,学院在标准均值的定义,"不要指望这个到处都一样的工作方式。"P></

    如果你在"多对多"的赌徒,发动机将JSON和简单的使用duplication allow the last至指定的值。本:P></

    1
    var o = {"a": 1,"b": 2,"a": 3}

    这becomes:P></

    1
    Object {a: 3, b: 2}

    但如果你不是赌徒,不要指望它!P></


    发布和回答是因为有很多过时的想法和对标准的混淆。截至2017年12月,有两个竞争标准:

    RFC 8259-https://tools.ietf.org/html/rfc8259

    ECMA-404-http://www.ecma-international.org/publications/files/ecma-st/ecma-404.pdf

    json.org建议ECMA-404是标准配置,但该站点似乎不是权威。虽然我认为将ECMA视为权威是公平的,但这里重要的是,标准(关于唯一密钥)之间的唯一区别是,RFC8259表示密钥应该是唯一的,而ECMA-404则表示它们不需要是唯一的。

    RCF-8259:

    "The names within an object SHOULD be unique."

    在所有类似的大写字母中,单词"should"在RFC世界中具有特定的含义,这在另一个标准(bcp 14,RFC 2119-https://tools.ietf.org/html/rfc2119)中被具体定义为,

  • SHOULD This word, or the adjective"RECOMMENDED", mean that
    there may exist valid reasons in particular circumstances to ignore
    a particular item, but the full implications must be understood and
    carefully weighed before choosing a different course.
  • ECMA-404:

    "The JSON syntax does not impose any restrictions on the strings used
    as names, does not require that name strings be unique, and does not
    assign any significance to the ordering of name/value pairs."

    所以,不管您如何分割它,它都是语法上有效的JSON。

    RFC 8259中唯一密钥建议的原因是,

    An object whose names are all unique is interoperable in the sense
    that all software implementations receiving that object will agree on
    the name-value mappings. When the names within an object are not
    unique, the behavior of software that receives such an object is
    unpredictable. Many implementations report the last name/value pair
    only. Other implementations report an error or fail to parse the
    object, and some implementations report all of the name/value pairs,
    including duplicates.

    换句话说,从RFC8259的观点来看,它是有效的,但是您的解析器可能会出错,并且对于哪个值(如果有的话)将与该键配对没有任何承诺。从ECMA-404的观点(我个人认为是权威),它是有效的,句号。对我来说,这意味着任何拒绝解析它的解析器都会被破坏。它至少应该根据这两个标准进行解析。但是,在任何情况下,它是如何变成您选择的本机对象的,不管是否是唯一的键,都完全取决于环境和情况,而且这些都不是标准中的标准。


    标准说:This does theP></

    Programming languages vary widely on whether they support objects, and
    if so, what characteristics and constraints the objects offer. The
    models of object systems can be wildly divergent and are continuing to
    evolve. JSON instead provides a simple notation for expressing
    collections of name/value pairs. Most programming languages will have
    some feature for representing such collections, which can go by names
    like record, struct, dict, map, hash, or object.

    在node.js is the least臭虫。这succeeds node.js队列中。P></

    1
    2
    3
    4
    5
    6
    try {
         var json = {"name":"n","name":"v"};
         console.log(json); // outputs { name: 'v' }
    } catch (e) {
         console.log(e);
    }


    如果你在C # deserialise to a / the last value Dictionary需要对密钥:P></

    1
    2
    3
    string json = @"{""a"":""x"",""a"":""y""}";
    var d = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
    // {"a" :"y" }

    如果你试图deserialise toP></

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    class Foo
    {
        [JsonProperty("a")]
        public string Bar { get; set; }

        [JsonProperty("a")]
        public string Baz { get; set; }
    }

    var f = JsonConvert.DeserializeObject<Foo>(json);

    你得到Newtonsoft.Json.JsonSerializationException例外。P></