Iterate over an array of JSON objects with jsoncpp

John S. picture John S. · Jun 8, 2017 · Viewed 11.9k times · Source

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

Answer

Sga picture Sga · Jul 11, 2017

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