简体   繁体   中英

Why jsoncpp append function will cause an assert error

I am a newer to Jsoncpp and I used it in my c++ projects。Sometimes I found a wired error like this:

Json::Value val;
val["1"] = 1;
val["2"] = 2;

Json::Value arr;
arr["name"] = "wjx";
arr["age"] = 23;
arr["id"] = 17777;

val.append(arr);

this will cause a error named Json::throwLogicError,But the similar code below run rightly

Json::Value val;
val["first"] = 1;
val["second"] = 2;

val["fourth"] = "wjx";

Json::Value root;
root.append(val);

I don't konw the reason,And I find no talk on the Internet so I ask for help.Who can explain this sitution.

append only makes sense for arrayValue , that is list-type JSON values.

When jsoncpp creates a value, by default, it starts as a nullValue . If you then perform array-style operations on it like append , it'll turn it into an arrayValue and carry on. This is what happens when you write

Json::Value root; // Root starts as a nullValue
root.append(val); // Root becomes an arrayValue
                  // and from now on array-type behaviors are okay

But that doesn't work in your first code snippet. Because similarly to append causing a conversion from nullValue to arrayValue , using operator[] with string keys to do assignment converts it into an objectValue , a collection of key-value pairs. ( operator[] with integer keys would have turned it into an arrayValue , since in a JSON object keys must be strings.)

Json::Value val; // val starts as a nullValue
val["1"] = 1;    // val becomes an objectValue
                 // and from now on dict-style operations are okay
val["2"] = 2;

...

val.append(arr); // ERROR: val only accepts dict-style operations

To see why a dict-style Value can't accept append , ask yourself what key should be associated with the value you're append ing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM