Reputation: 4709
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.
Upvotes: 4
Views: 822
Reputation: 1130
The JsonCpp parser allows since some time to error out on duplicate keys, by configuring its reader-builder:
Json::CharReaderBuilder myReader;
myReader["rejectDupKeys"] = true;
See the documentation in reader.h
in the jsoncpp github repo. This is a github permalink, so maybe you need to check for a newer version of that file. There's also a github issue where that problem was addressed.
Upvotes: 0
Reputation: 484
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.
Upvotes: 1
Reputation: 5516
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.
Upvotes: 3