6

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

2 Answers 2

18

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());
Sign up to request clarification or add additional context in comments.

Comments

2

Alternatively to what @Sga suggested I would recommend using a ranged for loop:

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

I find this to be more readable plus it saves the extra call on size() as well as the index-wise retrieval.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.