JSON语法是否允许在对象中使用重复键?

时间:2022-11-23 09:04:07

Is this valid json?

这是有效的json吗?

{
    "a" : "x",
    "a" : "y"
}

http://jsonlint.com/ says yes.

http://jsonlint.com/说,是的。

http://www.json.org/ doesn't say anything about it being forbidden.

http://www.json.org/并没有说任何关于它被禁止的事情。

But obviously it doesn't make much sense, does it? Most implementations probably use a hashtable so it is being overriden anyways.

但显然这没有多大意义,对吧?大多数实现可能使用hashtable,因此无论如何它都被覆盖了。

11 个解决方案

#1


80  

From the standard (p. ii):

标准(p. ii):

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.

预计其他标准将参考这个标准,严格遵循JSON文本格式,同时对各种编码细节进行限制。这些标准可能需要特定的行为。JSON本身不指定任何行为。

Further down in the standard (p. 2), the specification for a JSON object:

在标准的后面(第2页),JSON对象的规范:

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.

对象结构表示为一对围绕0或更多名称/值对的花括号标记。名称是字符串。每个名称后面都有一个冒号,将名称与值分开。一个逗号标记将值与以下名称分隔开。

JSON语法是否允许在对象中使用重复键?

It does not make any mention of duplicate keys being invalid or valid, so according to the specification I would safely assume that means they are allowed.

它没有提到重复的键是无效的或有效的,因此根据规范,我可以安全地假设它们是允许的。

That most implementations of JSON libraries do not accept duplicate keys does not conflict with the standard, because of the first quote.

JSON库的大多数实现不接受重复键,这与标准不冲突,因为第一个引号。

Here are two examples related to the C++ standard library. When deserializing some JSON object into a std::map it would make sense to refuse duplicate keys. But when deserializing some JSON object into a std::multimap it would make sense to accept duplicate keys as normal.

这里有两个与c++标准库相关的示例。当将一些JSON对象反序列化为std::map时,拒绝重复的键是有意义的。但是,当将一些JSON对象反序列化为std::multimap时,正常地接受重复键是有意义的。

#2


84  

The short answer: Yes but is not recommended.
The long answer: It depends on what you call valid...

简短的回答:是的,但不推荐。长话短说:这取决于你所说的有效……


The JSON Data Interchange Format (ECMA-404) doesn't say anything about duplicated names (keys).

JSON数据交换格式(ECMA-404)没有提到重复的名称(键)。

However, The JavaScript Object Notation (JSON) Data Interchange Format) (RFC7159) says:

但是,JavaScript对象表示法(JSON)数据交换格式(RFC7159)表示:

The names within an object SHOULD be unique.

对象中的名称应该是唯一的。

In this context should must be understood as specified in RFC 2119

在这种情况下,必须理解RFC 2119中规定的内容

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 why unique names (keys) are good:

RFC 7159解释了为什么唯一的名字(键)是好的:

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.

对JSON解析库的观察表明,它们是否使调用软件可见的对象成员排序存在差异。其行为不依赖于成员排序的实现将是可互操作的,因为它们不会受到这些差异的影响。



Trying to parse a string with duplicated names with the Java implementation by Douglas Crockford (the creator of JSON) results in an exception:

试图用Douglas Crockford (JSON的创建者)的Java实现解析一个名称重复的字符串,结果出现了一个例外:

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

#3


13  

There are 2 documents specifying the JSON format:

有2个文档指定JSON格式:

  1. http://json.org/
  2. http://json.org/
  3. https://tools.ietf.org/html/rfc7159
  4. https://tools.ietf.org/html/rfc7159

The accepted answer quotes from the 1st document. I think the 1st document is more clear, but the 2nd contains more detail.

从第一个文档中接受的答案引用。我认为第一份文件更清晰,但第二份文件包含更多细节。

The 2nd document says:

第二个文档说:

  1. 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.

    对象结构表示为一对围绕0或更多名称/值对(或成员)的花括号。名称是字符串。每个名称后面都有一个冒号,将名称与值分隔开。一个逗号将值与下面的名称分隔开。对象中的名称应该是唯一的。

So it is not forbidden to have a duplicate name, but it is discouraged.

因此,有一个重复的名字是不被禁止的,但是它是不被鼓励的。

#4


8  

I came across a similar question when dealing with an API that accepts both XML and JSON, but doesn't document how it would handle what you'd expect to be duplicate keys in the JSON accepted.

在处理既接受XML又接受JSON的API时,我遇到了一个类似的问题,但并没有说明如何处理JSON所接受的重复键。

The following is a valid XML representation of your sample JSON:

下面是示例JSON的有效XML表示:

<object>
  <a>x</a>
  <a>y</a>
</object>

When this is converted into JSON, you get the following:

当它转换为JSON时,您将得到以下内容:

{
  "object": {
    "a": [
      "x",
      "y"
    ]
  }
}

A natural mapping from a language that handles what you might call duplicate keys to another, can serve as a potential best practice reference here.

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

Hope that helps someone!

希望能帮助一些人!

#5


6  

The JSON spec says this:

JSON规范是这样说的:

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

对象是一组无序的名称/值对。

The important part here is "unordered": it implies uniqueness of keys, because the only thing you can use to refer to a specific pair is its key.

这里的重要部分是“无序的”:它意味着键的惟一性,因为您惟一可以用来引用特定对的就是它的键。

In addition, most JSON libs will deserialize JSON objects to hash maps/dictionaries, where keys are guaranteed unique. What happens when you deserialize a JSON object with duplicate keys depends on the library: in most cases, you'll either get an error, or only the last value for each duplicate key will be taken into account.

此外,大多数JSON libs会将JSON对象反序列化为散列映射/字典,其中的键是惟一的。当您使用重复键反序列化JSON对象时,会发生什么情况取决于库:在大多数情况下,您要么会得到一个错误,要么会考虑到每个重复键的最后一个值。

For example, in Python, json.loads('{"a": 1, "a": 2}') returns {"a": 2}.

例如,在Python中,json。load ('{"a": 1, "a": 2})返回{"a": 2}。

#6


2  

Asking for purpose, there are different answers:

问目标,有不同的答案:

Using JSON to serialize objects (JavaScriptObjectNotation), each dictionary element maps to an indivual object property, so different entries defining a value for the same property has no meaning.

使用JSON序列化对象(javascript tobjectnotation),每个字典元素都映射到一个独立对象属性,因此定义相同属性值的不同条目没有任何意义。

However, I came over the same question from a very specific use case: Writing JSON samples for API testing, I was wondering how to add comments into our JSON file without breaking the usability. The JSON spec does not know comments, so I came up with a very simple approach:

然而,我从一个非常具体的用例中遇到了同样的问题:为API测试编写JSON样本,我想知道如何在不破坏可用性的情况下将注释添加到我们的JSON文件中。JSON规范不知道注释,所以我想出了一个非常简单的方法:

To use duplicate keys to comment our JSON samples. Example:

要使用重复的键来注释我们的JSON示例。例子:

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

{"property1": "value1", "备注":"…prop1控制……", "property2": "value2", "备注":"…value2提出了一个例外……”,}

The JSON serializers which we are using have no problems with these "REMARK" duplicates and our application code simply ignores this little overhead.

我们正在使用的JSON序列化器对于这些“备注”重复没有问题,我们的应用程序代码只是忽略了这个小开销。

So, even though there is no meaning on the application layer, these duplicates for us provide a valuable workaround to add comments to our testing samples without breaking the usability of the JSON.

因此,即使在应用层上没有任何意义,这些副本也为我们提供了一个宝贵的解决方案,可以在不破坏JSON可用性的情况下向我们的测试示例添加注释。

#7


2  

SHOULD be unique does not mean MUST be unique. However, as stated, some parsers would fail and others would just use the last value parsed. However, if the spec was cleaned up a little to allow for duplicates then I could see a use where you may have an event handler which is transforming the JSON to HTML or some other format...in such cases it would be perfectly valid to parse the JSON and create another document format...

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

[
  "div":
  {
    "p":"hello",
    "p":"universe"
  }
  "div":
  {
    "h1":"Heading 1",
    "p":"another paragraph"
  }
]

could then easily parse to html for example

然后可以很容易地解析到html例如

<body>
 <div>
  <p>hello</p>
  <p>universe</p>
 </div>
 <div>
  <h1>Heading 1</h1>
  <p>another paragraph</p>
 </div>
</body>

I can see the reasoning behind the question but as it stands...I wouldn't trust it.

我能看出这个问题背后的原因,但就目前而言……我不相信它。

#8


1  

It's not defined in the ECMA JSON standard. And generally speaking, a lack of definition in a standard means, "Don't count on this working the same way everywhere."

它在ECMA JSON标准中没有定义。一般来说,缺乏标准的定义意味着,“不要指望它在任何地方都以同样的方式工作。”

If you're a gambler, "many" JSON engines will allow duplication and simply use the last-specified value. This:

如果您是赌徒,“许多”JSON引擎将允许复制,并只使用最后指定的值。这样的:

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

Becomes this:

变成这样:

Object {a: 3, b: 2}

But if you're not a gambler, don't count on it!

但如果你不是赌徒,那就别指望了!

#9


1  

According to RFC-7159, the current standard for JSON published by the Internet Engineering Task Force (IETF), states "The names within an object SHOULD be unique". However, according to RFC-2119 which defines the terminology used in IETF documents, the word "should" in fact means "... 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." What this essentially means is that while having unique keys is recommended, it is not a must. We can have duplicate keys in a JSON object, and it would still be valid.

根据Internet Engineering Task Force (IETF)发布的当前JSON标准RFC-7159,声明“对象内部的名称应该是唯一的”。然而,根据RFC-2119定义IETF文档中使用的术语,单词“应该”实际上意味着“……”在特定的情况下,可能有合理的理由忽视某一项目,但在选择不同的路线之前,必须了解和仔细权衡其全部含义。”这本质上意味着,虽然推荐使用唯一的键,但它不是必须的。我们可以在JSON对象中使用重复的键,它仍然是有效的。

From practical application, I have seen the value from the last key is considered when duplicate keys are found in a JSON.

从实际应用中,我看到当在JSON中发现重复的键时,考虑上一个键的值。

#10


0  

In C# if you deserialise to a Dictionary<string, string> it takes the last key value pair:

在c#中,如果对字典 进行反序列化,它将取最后一个键值对: ,>

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

if you try to deserialise to

如果你试图反序列化。

class Foo
{
    [JsonProperty("a")]
    public string Bar { get; set; }

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

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

you get a Newtonsoft.Json.JsonSerializationException exception.

你会得到一个Newtonsoft.Json。JsonSerializationException例外。

#11


0  

The standard does say this:

标准是这样说的:

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.

编程语言在是否支持对象以及如果支持对象,以及对象提供的特性和约束方面存在很大差异。对象系统的模型可能有很大的差异,而且还在不断发展。JSON为表示名称/值对的集合提供了一个简单的符号。大多数编程语言都有一些用于表示此类集合的特性,这些集合可以按诸如记录、结构、敕令、映射、散列或对象等名称进行排列。

The bug is in node.js at least. This code succeeds in node.js.

错误在节点中。js至少。此代码在node.js中成功。

try {
     var json = {"name":"n","name":"v"};
     console.log(json); // outputs { name: 'v' }
} catch (e) {
     console.log(e);
}

#1


80  

From the standard (p. ii):

标准(p. ii):

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.

预计其他标准将参考这个标准,严格遵循JSON文本格式,同时对各种编码细节进行限制。这些标准可能需要特定的行为。JSON本身不指定任何行为。

Further down in the standard (p. 2), the specification for a JSON object:

在标准的后面(第2页),JSON对象的规范:

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.

对象结构表示为一对围绕0或更多名称/值对的花括号标记。名称是字符串。每个名称后面都有一个冒号,将名称与值分开。一个逗号标记将值与以下名称分隔开。

JSON语法是否允许在对象中使用重复键?

It does not make any mention of duplicate keys being invalid or valid, so according to the specification I would safely assume that means they are allowed.

它没有提到重复的键是无效的或有效的,因此根据规范,我可以安全地假设它们是允许的。

That most implementations of JSON libraries do not accept duplicate keys does not conflict with the standard, because of the first quote.

JSON库的大多数实现不接受重复键,这与标准不冲突,因为第一个引号。

Here are two examples related to the C++ standard library. When deserializing some JSON object into a std::map it would make sense to refuse duplicate keys. But when deserializing some JSON object into a std::multimap it would make sense to accept duplicate keys as normal.

这里有两个与c++标准库相关的示例。当将一些JSON对象反序列化为std::map时,拒绝重复的键是有意义的。但是,当将一些JSON对象反序列化为std::multimap时,正常地接受重复键是有意义的。

#2


84  

The short answer: Yes but is not recommended.
The long answer: It depends on what you call valid...

简短的回答:是的,但不推荐。长话短说:这取决于你所说的有效……


The JSON Data Interchange Format (ECMA-404) doesn't say anything about duplicated names (keys).

JSON数据交换格式(ECMA-404)没有提到重复的名称(键)。

However, The JavaScript Object Notation (JSON) Data Interchange Format) (RFC7159) says:

但是,JavaScript对象表示法(JSON)数据交换格式(RFC7159)表示:

The names within an object SHOULD be unique.

对象中的名称应该是唯一的。

In this context should must be understood as specified in RFC 2119

在这种情况下,必须理解RFC 2119中规定的内容

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 why unique names (keys) are good:

RFC 7159解释了为什么唯一的名字(键)是好的:

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.

对JSON解析库的观察表明,它们是否使调用软件可见的对象成员排序存在差异。其行为不依赖于成员排序的实现将是可互操作的,因为它们不会受到这些差异的影响。



Trying to parse a string with duplicated names with the Java implementation by Douglas Crockford (the creator of JSON) results in an exception:

试图用Douglas Crockford (JSON的创建者)的Java实现解析一个名称重复的字符串,结果出现了一个例外:

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

#3


13  

There are 2 documents specifying the JSON format:

有2个文档指定JSON格式:

  1. http://json.org/
  2. http://json.org/
  3. https://tools.ietf.org/html/rfc7159
  4. https://tools.ietf.org/html/rfc7159

The accepted answer quotes from the 1st document. I think the 1st document is more clear, but the 2nd contains more detail.

从第一个文档中接受的答案引用。我认为第一份文件更清晰,但第二份文件包含更多细节。

The 2nd document says:

第二个文档说:

  1. 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.

    对象结构表示为一对围绕0或更多名称/值对(或成员)的花括号。名称是字符串。每个名称后面都有一个冒号,将名称与值分隔开。一个逗号将值与下面的名称分隔开。对象中的名称应该是唯一的。

So it is not forbidden to have a duplicate name, but it is discouraged.

因此,有一个重复的名字是不被禁止的,但是它是不被鼓励的。

#4


8  

I came across a similar question when dealing with an API that accepts both XML and JSON, but doesn't document how it would handle what you'd expect to be duplicate keys in the JSON accepted.

在处理既接受XML又接受JSON的API时,我遇到了一个类似的问题,但并没有说明如何处理JSON所接受的重复键。

The following is a valid XML representation of your sample JSON:

下面是示例JSON的有效XML表示:

<object>
  <a>x</a>
  <a>y</a>
</object>

When this is converted into JSON, you get the following:

当它转换为JSON时,您将得到以下内容:

{
  "object": {
    "a": [
      "x",
      "y"
    ]
  }
}

A natural mapping from a language that handles what you might call duplicate keys to another, can serve as a potential best practice reference here.

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

Hope that helps someone!

希望能帮助一些人!

#5


6  

The JSON spec says this:

JSON规范是这样说的:

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

对象是一组无序的名称/值对。

The important part here is "unordered": it implies uniqueness of keys, because the only thing you can use to refer to a specific pair is its key.

这里的重要部分是“无序的”:它意味着键的惟一性,因为您惟一可以用来引用特定对的就是它的键。

In addition, most JSON libs will deserialize JSON objects to hash maps/dictionaries, where keys are guaranteed unique. What happens when you deserialize a JSON object with duplicate keys depends on the library: in most cases, you'll either get an error, or only the last value for each duplicate key will be taken into account.

此外,大多数JSON libs会将JSON对象反序列化为散列映射/字典,其中的键是惟一的。当您使用重复键反序列化JSON对象时,会发生什么情况取决于库:在大多数情况下,您要么会得到一个错误,要么会考虑到每个重复键的最后一个值。

For example, in Python, json.loads('{"a": 1, "a": 2}') returns {"a": 2}.

例如,在Python中,json。load ('{"a": 1, "a": 2})返回{"a": 2}。

#6


2  

Asking for purpose, there are different answers:

问目标,有不同的答案:

Using JSON to serialize objects (JavaScriptObjectNotation), each dictionary element maps to an indivual object property, so different entries defining a value for the same property has no meaning.

使用JSON序列化对象(javascript tobjectnotation),每个字典元素都映射到一个独立对象属性,因此定义相同属性值的不同条目没有任何意义。

However, I came over the same question from a very specific use case: Writing JSON samples for API testing, I was wondering how to add comments into our JSON file without breaking the usability. The JSON spec does not know comments, so I came up with a very simple approach:

然而,我从一个非常具体的用例中遇到了同样的问题:为API测试编写JSON样本,我想知道如何在不破坏可用性的情况下将注释添加到我们的JSON文件中。JSON规范不知道注释,所以我想出了一个非常简单的方法:

To use duplicate keys to comment our JSON samples. Example:

要使用重复的键来注释我们的JSON示例。例子:

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

{"property1": "value1", "备注":"…prop1控制……", "property2": "value2", "备注":"…value2提出了一个例外……”,}

The JSON serializers which we are using have no problems with these "REMARK" duplicates and our application code simply ignores this little overhead.

我们正在使用的JSON序列化器对于这些“备注”重复没有问题,我们的应用程序代码只是忽略了这个小开销。

So, even though there is no meaning on the application layer, these duplicates for us provide a valuable workaround to add comments to our testing samples without breaking the usability of the JSON.

因此,即使在应用层上没有任何意义,这些副本也为我们提供了一个宝贵的解决方案,可以在不破坏JSON可用性的情况下向我们的测试示例添加注释。

#7


2  

SHOULD be unique does not mean MUST be unique. However, as stated, some parsers would fail and others would just use the last value parsed. However, if the spec was cleaned up a little to allow for duplicates then I could see a use where you may have an event handler which is transforming the JSON to HTML or some other format...in such cases it would be perfectly valid to parse the JSON and create another document format...

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

[
  "div":
  {
    "p":"hello",
    "p":"universe"
  }
  "div":
  {
    "h1":"Heading 1",
    "p":"another paragraph"
  }
]

could then easily parse to html for example

然后可以很容易地解析到html例如

<body>
 <div>
  <p>hello</p>
  <p>universe</p>
 </div>
 <div>
  <h1>Heading 1</h1>
  <p>another paragraph</p>
 </div>
</body>

I can see the reasoning behind the question but as it stands...I wouldn't trust it.

我能看出这个问题背后的原因,但就目前而言……我不相信它。

#8


1  

It's not defined in the ECMA JSON standard. And generally speaking, a lack of definition in a standard means, "Don't count on this working the same way everywhere."

它在ECMA JSON标准中没有定义。一般来说,缺乏标准的定义意味着,“不要指望它在任何地方都以同样的方式工作。”

If you're a gambler, "many" JSON engines will allow duplication and simply use the last-specified value. This:

如果您是赌徒,“许多”JSON引擎将允许复制,并只使用最后指定的值。这样的:

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

Becomes this:

变成这样:

Object {a: 3, b: 2}

But if you're not a gambler, don't count on it!

但如果你不是赌徒,那就别指望了!

#9


1  

According to RFC-7159, the current standard for JSON published by the Internet Engineering Task Force (IETF), states "The names within an object SHOULD be unique". However, according to RFC-2119 which defines the terminology used in IETF documents, the word "should" in fact means "... 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." What this essentially means is that while having unique keys is recommended, it is not a must. We can have duplicate keys in a JSON object, and it would still be valid.

根据Internet Engineering Task Force (IETF)发布的当前JSON标准RFC-7159,声明“对象内部的名称应该是唯一的”。然而,根据RFC-2119定义IETF文档中使用的术语,单词“应该”实际上意味着“……”在特定的情况下,可能有合理的理由忽视某一项目,但在选择不同的路线之前,必须了解和仔细权衡其全部含义。”这本质上意味着,虽然推荐使用唯一的键,但它不是必须的。我们可以在JSON对象中使用重复的键,它仍然是有效的。

From practical application, I have seen the value from the last key is considered when duplicate keys are found in a JSON.

从实际应用中,我看到当在JSON中发现重复的键时,考虑上一个键的值。

#10


0  

In C# if you deserialise to a Dictionary<string, string> it takes the last key value pair:

在c#中,如果对字典 进行反序列化,它将取最后一个键值对: ,>

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

if you try to deserialise to

如果你试图反序列化。

class Foo
{
    [JsonProperty("a")]
    public string Bar { get; set; }

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

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

you get a Newtonsoft.Json.JsonSerializationException exception.

你会得到一个Newtonsoft.Json。JsonSerializationException例外。

#11


0  

The standard does say this:

标准是这样说的:

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.

编程语言在是否支持对象以及如果支持对象,以及对象提供的特性和约束方面存在很大差异。对象系统的模型可能有很大的差异,而且还在不断发展。JSON为表示名称/值对的集合提供了一个简单的符号。大多数编程语言都有一些用于表示此类集合的特性,这些集合可以按诸如记录、结构、敕令、映射、散列或对象等名称进行排列。

The bug is in node.js at least. This code succeeds in node.js.

错误在节点中。js至少。此代码在node.js中成功。

try {
     var json = {"name":"n","name":"v"};
     console.log(json); // outputs { name: 'v' }
} catch (e) {
     console.log(e);
}