c++ - Parse elements from array in json file using boost -


i have json file looks this:

{         "type": "2d",         "data":         [             [                 "26",                 "17",                 "1"             ],             [                 "13",                 "29",                 "1"             ],             [                 "13",                 "30",                 "1"             ], .... 

in data, each array have meaning need assign variable each 1 (in loop), like:

int first = 26; int second = 17; int third = 1; 

i doing (i defined before v):

boost_foreach(boost::property_tree::ptree::value_type &v2, v.second.get_child("data")) {   boost_foreach (boost::property_tree::ptree::value_type& itempair, v2.second) {   cout << itempair.second.get_value<std::string>() << " ";       }   }  } 

just print each variable, handle have them set, not each one. have idea how it?

thanks in advance!

for json arrays, data node contains multiple child nodes empty name (docs: c++ how read xml using boost xml parser , store in map).

so loop through child nodes (optionally checking key == "").

here's simplist example. used trick array map elements local variables one, two, three. consider using translator or "parse" function parses tree node struct { int first,second, third; } instead (e.g. https://stackoverflow.com/a/35318635/85371)

live on coliru

#include <boost/property_tree/json_parser.hpp> #include <iostream>  int main() {     boost::property_tree::ptree pt;     read_json("input.txt", pt);      using namespace std;     for(auto& array3 : pt.get_child("data")) {         int first, second, third;         int* const elements[3] = { &first, &second, &third };         auto element = begin(elements);          (auto& : array3.second) {             **element++ = i.second.get_value<int>();              if (element == end(elements)) break;         }          std::cout << "first:" << first << " second:" << second << " third:" << third << "\n";     } } 

for input {"type":"2d","data":[["26","17","1"],["13","29","1"],["13","30","1"]]} prints:

first:26 second:17 third:1 first:13 second:29 third:1 first:13 second:30 third:1 

Comments

Popular posts from this blog

java - Suppress Jboss version details from HTTP error response -

gridview - Yii2 DataPorivider $totalSum for a column -

Sass watch command compiles .scss files before full sftp upload -