C++ Poco - How to iterate thought a JSON array?

Viewed 3778

I've seen some examples how to iterate thought nested JSON objects like:

 "{ \"test\" : { \"property\" : \"value\" } }"

But now I need to iterate through a JSON array (the children array below):

"{ \"name\" : \"Franky\", \"children\" : [ \"Jonas\", \"Ellen\" ] }"

How can I achieve this?

I can't see anywhere an example or even on the POCO documentation.

I have this sample below, but can't get the array of children.

Poco::Dynamic::Var test = object->get("children");

Poco::JSON::Array::Ptr subObject = test.extract<Poco::JSON::Array::Ptr>();

for (it = subObject->begin(); it != subObject->end(); it++) // how to iterate here?
{
    std::cout << "my children:" << it->first << "\n";
}
1 Answers

Methods begin and end of your subObject array return JSON::Array::ConstIterator which is defined as follows

typedef std::vector<Dynamic::Var>::const_iterator ConstIterator;

so you can write

for (Poco::JSON::Array::ConstIterator it= subObject->begin(); it != subObject->end(); ++it)
{
  // do sth here
}

and when you know that it points to Dynamic::Var you can use convert or extract method to get string object:

for (Poco::JSON::Array::ConstIterator it = subObject->begin(); it != subObject->end(); ++it)
{
    std::cout << "my children:" << it->convert<std::string>() << "\n";
}
Related