Jean-Philippe Pellet
Jean-Philippe Pellet

Reputation: 60006

Are double definitions allowed in JSON, and if so, how should they be interpreted?

Is this valid JSON?

{
  "name": "foo",
  "name": "bar"
}

If so, how should it be interpreted?

Upvotes: 2

Views: 150

Answers (5)

phihag
phihag

Reputation: 288200

It's technically legal, but strongly discouraged, according to the RFC:

The names within an object SHOULD be unique.

You can go one of two routes:

  • The JavaScript route: In JavaScript, this is illegal. Since JSON is supposed to be a subset, reject the input as invalid.
  • The Postel/Python route: Overwrite the "var" entry with the latest value.

Upvotes: 7

Rob
Rob

Reputation: 5286

According to RFC 4627, duplicate names are discouraged. See section 2.2. Objects:

The names within an object SHOULD be unique.

The above URL also refers us to RFC 2119, which specifies how the word SHOULD is interpreted:

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.

However, many parsers & JSON APIs implement this as SHOULD ALWAYS, and throw an error or ignore multiple values upon encountering duplicate properties. This includes jQuery.parseJSON() as well as .NET's JSON serialization.

Upvotes: 2

sica07
sica07

Reputation: 4956

No, is not. You have two attributes with the same label/name/title. Here is a very simple and short explanation of the JSON

Upvotes: 0

Baz1nga
Baz1nga

Reputation: 15579

JSon object, like any other object, can not have two attribute with same name. That's illegal in the same way as having same key twice in a map.

JSONObject would throw an exception if you have two keys with same name in one object. You may want to alter your object so that keys are not repeated under same object.

In this case the change would be to make your json key name have value as an array

Upvotes: 0

Prisoner
Prisoner

Reputation: 27628

It is not valid JSON as there are two name variables. Take a read of this to help you understand JSON a bit better.

Upvotes: 0

Related Questions