Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate over an array of JSON objects with jsoncpp

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
like image 817
John S. Avatar asked Jun 08 '17 18:06

John S.


1 Answers

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());
like image 67
Sga Avatar answered Nov 13 '22 02:11

Sga