Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
478 views
in Technique[技术] by (71.8m points)

standards - Does JSON syntax allow duplicate keys in an object?

Is this valid json?

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

http://jsonlint.com/ says yes.

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

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

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


[ECMA-404][1] "The JSON Data Interchange Syntax" doesn't say anything about duplicated names (keys).
However, [RFC 8259][2] "The JavaScript Object Notation (JSON) Data Interchange Format" says:

The names within an object SHOULD be unique.

In this context SHOULD must be understood as specified in BCP 14:

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 8259][2] explains why unique names (keys) are good: > 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.

Also, as Serguei pointed out in the comments: ECMA-262 "ECMAScript? Language Specification", reads:

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.


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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...