From the fragment of Alex, which indexes into a Json array, I created a working example and added a loop over Json array.
Compiles with
g++ -std=c++20 -o json-array-poco json-array-poco.cpp -lPocoRedis -lPocoUtil -lPocoNet -lPocoNetSSL -lPocoCrypto -lPocoXML -lPocoJSON -lPocoFoundation
Requires
sudo apt install libpoco-dev
Store into json-array-poco.cpp
#include <iostream>
#include <Poco/JSON/JSON.h>
#include <Poco/JSON/Parser.h>
#include <stack>
using Poco::JSON::Parser;
using std::cout;
using std::stack;
using std::string;
void example_index_into_array (){
Parser parser;
string json_string = R"( {"data":[{"p":11,"t":1111},{"p":22,"t":2222}],"foo":"bar"} )";
auto json_pocojson = parser.parse(json_string).extract<Poco::JSON::Object::Ptr>(); // Specify type as Json
auto foo_string = json_pocojson->get("foo").extract<string>(); // Specify type as string
auto data_pjarray = json_pocojson->get("data").extract<Poco::JSON::Array::Ptr>(); // Specify type as Json array
auto item_0 = data_pjarray->getObject(0);
auto item_1 = data_pjarray->getObject(1);
assert (foo_string == "bar");
assert (item_0->getValue<int64_t>("t") == 1111);
assert (item_1->getValue<int64_t>("t") == 2222);
assert (item_0->getValue<int64_t>("p") == 11);
assert (item_1->getValue<int64_t>("p") == 22);
}
void example_loop_over_array (){
Parser parser;
string json_string = R"( {"data":[{"p":11,"t":1111},{"p":22,"t":2222}],"foo":"bar"} )";
auto json_pocojson = parser.parse(json_string).extract<Poco::JSON::Object::Ptr>(); // Specify type as Json
auto data_pjarray = json_pocojson->get("data").extract<Poco::JSON::Array::Ptr>(); // Specify type as Json array
stack<int> t;
stack<int> p;
t.push(2222);
t.push(1111);
p.push(22);
p.push(11);
// The Poco JSON array is not a C11 range, so a range-base for loop errors on compile with
// this range-based 'for' statement requires a suitable "begin" function and none was foundC/C++(2291)
// The pre-range method is the only option
for (auto item_pjaiterator = data_pjarray->begin(); item_pjaiterator != data_pjarray->end(); ++item_pjaiterator) {
auto item_pocojson = item_pjaiterator->extract<Poco::JSON::Object::Ptr>();
assert (item_pocojson->get("t").extract<int64_t>() == t.top()); t.pop();
assert (item_pocojson->get("p").extract<int64_t>() == p.top()); p.pop();
}
}
int main() {
cout << "This is json-array-poco\n";
example_index_into_array();
example_loop_over_array();
return 0;
}