I have a following array of objects in JsonCpp::Value:
[{"foo": "bar", "baz": ["Hello", "World"]},
{"Hello": "99bottles", "baz": ["bar", "foo"]},
{"beer": "hello", "world": ["foo"]}.... ]
I have to iterate over them and alternate them (remove some elements, add another one).
I can easily iterate over JsonArray with:
for (Json::Value::ArrayIndex i = 0; i != array.size(); i++) {
doc[i] = Json::Value();
Json::Value result = array.get(i, Json::Value());
std::cout<<"-------------------"<<std::endl;
std::cout<<result.toStyledString()<<std::endl;
}
But array.get() returns a copy of object. I won't be able to modify the object itself. I can create a new array and fill it with new objects based on values from the original one but it will be very costly.
Is it possible to achieve my goal with JsonCpp "in place"? And avoid additional memory overhead?
You are using get()
which must return a value instead of a reference, because you can call with with an invalid i
and it will return the default value you provide. I.e. for an array of size 2, you should be able to call array.get(17, Json::Value())
and you'll get back a default initialized Json::Value
.
If you're certain the element exists, which is the case here, you can use array[i]
, which will give you a reference. Note that you need to change the type of result
to Json::Value &
as well, otherwise you'll still get a copy.
Note that this is all shown and explained in the API documentation for JsonCpp. I've never used this library myself, all the above info I got from that page.