Does JSON syntax allow duplicate keys in an object?

后端 未结 12 1928
青春惊慌失措
青春惊慌失措 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:06

    Asking for purpose, there are different answers:

    Using JSON to serialize objects (JavaScriptObjectNotation), each dictionary element maps to an indivual object property, so different entries defining a value for the same property has no meaning.

    However, I came over the same question from a very specific use case: Writing JSON samples for API testing, I was wondering how to add comments into our JSON file without breaking the usability. The JSON spec does not know comments, so I came up with a very simple approach:

    To use duplicate keys to comment our JSON samples. Example:

    { "property1" : "value1", "REMARK" : "... prop1 controls ...", "property2" : "value2", "REMARK" : "... value2 raises an exception ...", }

    The JSON serializers which we are using have no problems with these "REMARK" duplicates and our application code simply ignores this little overhead.

    So, even though there is no meaning on the application layer, these duplicates for us provide a valuable workaround to add comments to our testing samples without breaking the usability of the JSON.

提交回复
热议问题