Reputation: 4561
In a json file imported into my c++ program there is such structure as:
{
"a":"1",
"ec":[
{
"a":"0x00",
"s":[
{"a":"0xA0"},
{"a":"0xA1"},
],
"b":"v1"
},
{
"a":"0x01",
"s":[
{"a":"0xB0"},
{"a":"0xB1"},
],
"b":"v2"
}
]
}
I want to iterate over the "ec"
array and get the values of all "a"
and for each "a"
the same for its s
array
vector<string> ec_a; // should contain {"0x00","0x01"}
vector<string> a1_s; // should contain {"0xA0", "0xA1"}
vector<string> a2_s; // should contain {"0xB0","0xB1"}
first I get the size of ec
but from the docs I understood should use iterator for the rest
int n=j["ec"].size() // n = 2
for(auto it=j["ec"].begin();it!=j["ec"].end();++it){
if(it.key() == "a") ec_a.push_back(it.value());
}
but get this exception nlohmann::detail::invalid_iterator at memory location
I assume that j["ec"].begin()
is incorrect.
how should I do that, Thanks.
Upvotes: 7
Views: 23812
Reputation: 20579
it
is an iterator to a compound type. A compound type doesn't, by itself, have a "key."
What you are trying to achieve is much easier than you may have thought. You can try this:
std::vector<std::string> ec_a;
for (auto& elem : j["ec"])
ec_a.push_back(elem["a"]);
Upvotes: 9