使用jsoncpp遍历JSON对象数组 [英] Iterate over an array of JSON objects with jsoncpp
本文介绍了使用jsoncpp遍历JSON对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下类型的JSON对象数组,jsonArr说:
I have an array of JSON objects, jsonArr say, of the following kind:
[
{ "attr1" : "somevalue",
"attr2" : "someothervalue"
},
{ "attr1" : "yetanothervalue",
"attr2" : "andsoon"
},
...
]
我使用jsoncpp尝试遍历数组,并检查每个对象是否都有成员"attr1"
,在这种情况下,我想将相应的值存储在向量values
中.
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
.
我尝试过类似的事情
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"]));
}
}
但不断收到错误消息
libc++abi.dylib: terminating with uncaught exception of type Json::LogicError: in Json::Value::find(key, end, found): requires objectValue or nullValue
推荐答案
很容易解释:
for (Json::Value::ArrayIndex i = 0; i != root.size(); i++)
if (root[i].isMember("attr1"))
values.push_back(root[i]["attr1"].asString());
这篇关于使用jsoncpp遍历JSON对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文