使用jsoncpp迭代JSON对象数组

6

我有一个JSON对象数组,假设为jsonArr,其格式如下:

[
  { "attr1" : "somevalue",
    "attr2" : "someothervalue"
  },
  { "attr1" : "yetanothervalue",
    "attr2" : "andsoon"
  },
  ...
]

使用 jsoncpp,我正在尝试遍历数组并检查每个对象是否具有成员“attr1”,如果是,则希望将相应的值存储在向量“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
2个回答

18
相当容易理解。
for (Json::Value::ArrayIndex i = 0; i != root.size(); i++)
    if (root[i].isMember("attr1"))
        values.push_back(root[i]["attr1"].asString());

1

除了@Sga建议的方法,我建议使用范围for循环:

for (auto el : root)
{
  if (el.isMember("attr1"))
    values.push_back(el["attr1"].asString());
}

我觉得这种写法更易读,而且可以避免多余调用size()方法以及索引检索。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接