Iterate over an array of JSON objects with jsoncpp

牧云@^-^@ 提交于 2019-12-11 02:29:55

问题


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

回答1:


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());


来源:https://stackoverflow.com/questions/44442932/iterate-over-an-array-of-json-objects-with-jsoncpp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!