Do JSON keys need to be unique?

<>

This question already has an answer here:

Answers


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", "...", ... ]
}

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.


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.


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"}]}

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.


Need Your Help

How to specify in crontab by what user to run script?

ubuntu cron crontab

I have few crontab jobs that run under root, but that gives me some problems. For example all folders created in process of that cron job are under user root and group root.

HTML Agility pack - parsing tables

c# html html-parsing html-agility-pack

I want to use the HTML agility pack to parse tables from complex web pages, but I am somehow lost in the object model.