1

I have a json file that looks like this:

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

In data, each array have a meaning so I need to assign a variable to each one (in a loop), like:

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

I was doing something like this (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 to print each variable, but I handle only to have them as a set, not each one. Does anyone have an idea how to do it?

thanks in advance!

1 Answer 1

2

For JSON arrays, the data node contains multiple child nodes with empty name (docs: c++ How to read XML using boost xml parser and store in map).

So you would just loop through the child nodes (optionally checking that the key == "").

Here's my simplist example. I used a trick with an array to map elements to the local variables one, two, three. Consider using a translator or a "parse" function that parses a tree node into a 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);

        for (auto& i : 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
Sign up to request clarification or add additional context in comments.

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.