Do JSON keys need to be unique?

68,278

Solution 1

There is no "error" if you use more than one key with the same name, but in JSON, the last key with the same name is the one that is going to be used.

In your case, the key "name" would be better to contain an array as it's value, instead of having a number of keys "name". It doesn't make much sense the same object or "thing" to have two names, or two of the same properties that are in conflict.

E.g.:

{
  "name" : [ "JOHN", "JACK", "...", ... ]
}

Solution 2

From RFC 4627:

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.

Solution 3

jQuery is able to parse it. But if you try to access it, it's just giving back the last value.

Check out http://jsfiddle.net/MQmM4/2/

So, it's parsable, I guess, but the value gets overridden if you use the same key.

Solution 4

here is a possible solution using array. just use array index

the_json_array.getJSONObject(0);


{"nameList":
[{"name" : "JACK"},
{"name" : "JILL"},
{"name" : "JOHN"},
{"name" : "JENNY"},
{"name" : "JAMES"},
{"name" : "JIM"}]}

Solution 5

A JSON Object looks like the following

public JSONObject(Map<?, ?> map) {
    this.map = new HashMap<String, Object>();
    if (map != null) {
        for (final Entry<?, ?> e : map.entrySet()) {
            final Object value = e.getValue();
            if (value != null) {
                this.map.put(String.valueOf(e.getKey()), wrap(value));
            }
        }
    }
}

A JSON Object is basically a hashmap containing key value pair.

This is why you are getting overwritten each time. To avoid this

  1. Either you must have unique key values
  2. Or you should wrap the key value pair as individual objects into an array

Have a look at this JSON Object java implementation to know in depth about JSON.

Share:
68,278
littleK
Author by

littleK

Updated on June 28, 2021

Comments

  • littleK
    littleK almost 3 years

    The following question is related to a question that I had asked earlier: Help parsing simple JSON (using JSON for JAVA ME)

    Do JSON keys need to be unique? For example, I was having trouble parsing the following XML (with JSON ME):

    {
      "name" : "JACK",
      "name" : "JILL",
      "name" : "JOHN",
      "name" : "JENNY",
      "name" : "JAMES",
      "name" : "JIM"
    }
    

    And, apparently, its because the keys must be unique. I'm just wondering if thats true in all cases or not. For example, if I were using something other than JSON ME, would I be able to parse all of these names?

    Thanks.