Reputation: 531
I have an array of JSON objects, jsonArr say, of the following kind:
[
{ "attr1" : "somevalue",
"attr2" : "someothervalue"
},
{ "attr1" : "yetanothervalue",
"attr2" : "andsoon"
},
...
]
Using jsoncpp, I'm trying to iterate through the array and check whether each object has a member "attr1"
, in which case I would like to store the corresponding value in the vector values
.
I have tried things like
Json::Value root;
Json::Reader reader;
Json::FastWriter fastWriter;
reader.parse(jsonArr, root);
std::vector<std::string> values;
for (Json::Value::iterator it=root.begin(); it!=root.end(); ++it) {
if (it->isMember(std::string("attr1"))) {
values.push_back(fastWriter.write((*it)["uuid"]));
}
}
but keep getting an error message
libc++abi.dylib: terminating with uncaught exception of type Json::LogicError: in Json::Value::find(key, end, found): requires objectValue or nullValue
Upvotes: 6
Views: 19742
Reputation: 9691
Alternatively to what @Sga suggested I would recommend using a ranged for loop:
for (auto el : root)
{
if (el.isMember("attr1"))
values.push_back(el["attr1"].asString());
}
I find this to be more readable plus it saves the extra call on size()
as well as the index-wise retrieval.
Upvotes: 2
Reputation: 3658
Pretty self explanatory:
for (Json::Value::ArrayIndex i = 0; i != root.size(); i++)
if (root[i].isMember("attr1"))
values.push_back(root[i]["attr1"].asString());
Upvotes: 18