Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing JSON with duplicate keys (json-cpp)

Tags:

json

jsoncpp

I'm using JsonCpp v0.6.0 to parse the following JSON string:

{
   "3.7":"de305d54-75b4-431b-adb2-eb6b9e546011",
   "3.7":"de305d54-75b4-431b-adb2-eb6b9e546012",
   "3.8":"de305d54-75b4-431b-adb2-eb6b9e546013"
}

as follows:

    Json::Value  root;
    Json::Reader reader;

    // value contains the JSON string

    if (!reader.parse(value, root, false))
    {
        // parse error
    }

After the call to parse, root contains two entries in a map:

[0] first = "3.7", second = "de305d54-75b4-431b-adb2-eb6b9e546012",
[1] first = "3.8", second = "de305d54-75b4-431b-adb2-eb6b9e546013",

i.e. the first JSON record has been overwritten by the second. No errors are reported.

Is this behaviour expected? Is it correct?

I thought that an error might have been reported indicating that there is a duplicate key in the JSON string.

like image 284
ksl Avatar asked Oct 31 '25 01:10

ksl


2 Answers

Like the JSON RFC sad the object names (keys) should be unique.

The names within an object SHOULD be unique.

Also the RFC defines if they are not, the behavior is unpredictable.

See this quote from the RFC:

An object whose names are all unique is interoperable in the sense
that all software implementations receiving that object will agree on the name-value mappings. When the names within an object are not
unique, the behavior of software that receives such an object is
unpredictable. Many implementations report the last name/value pair
only. Other implementations report an error or fail to parse the
object, and some implementations report all of the name/value pairs,
including duplicates.

like image 197
Zelldon Avatar answered Nov 03 '25 09:11

Zelldon


I agree with what you say, but I think JsonCpp tries to be a helpful tool, not something that tries to scrape by with minimal conformance to the RFCs. It would make more sense if it either maintained the structure of the input stream, and supported duplicate keys, or (and this is what the OP and I'd expect) if it doesn't like it, to flag an error. Silently changing the structure is unhelpful, as a check for the validity of the JSON input would have to be made with some other JSON tool prior to sending it to JsonCpp.

like image 31
Spalteer Avatar answered Nov 03 '25 10:11

Spalteer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!