Does JSON syntax allow duplicate keys in an object?

后端 未结 12 1924
青春惊慌失措
青春惊慌失措 2020-11-22 00:05

Is this valid json?

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

http://jsonlint.com/ says yes.

http://www.json.org/ doesn\'t say anyth

12条回答
  •  攒了一身酷
    2020-11-22 00:12

    The JSON spec says this:

    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.

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

提交回复
热议问题