Reading JSON with Boost property_tree

I am trying to use Boost property tree

to parse a JSON file. Here is the JSON file

{
    "a": 1,
    "b": [{
        "b_a": 2,
        "b_b": {
            "b_b_a": "test"
        },
        "b_c": 0,
        "b_d": [{
            "b_d_a": 3,
            "b_d_b": {
                "b_d_c": 4
            },
            "b_d_c": "test",
            "b_d_d": {
                "b_d_d": 5
            }
        }],
        "b_e": null,
        "b_f": [{
            "b_f_a": 6
        }],
        "b_g": 7
    }],
    "c": 8
}

      

and MWE

#include <iostream>
#include <fstream>

#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>

namespace pt = boost::property_tree;

using namespace std;

int main()
{

    boost::property_tree::ptree jsontree;
    boost::property_tree::read_json("test.json", jsontree);

    int v0 = jsontree.get<int>("a");
    int v1 = jsontree.get<int>("c");
}

      

Question I currently know how to read external variables a

and c

. However, I find it difficult to read other levels like b_a, b_b_a, b_d_a

and so on. How can I do this with Boost? I'm not necessarily looking for a looping solution, just trying to figure out how to "extract" the internal variables.

I am open to using other libraries if they are optimal. But so far Boost looks promising to me.

+3


source to share


1 answer


To get nested elements, you can use path syntax, where each path component is split into "."

. This is a little tricky here because the child node b

is an array. Thus, you cannot do without a loop.

const pt::ptree& b = jsontree.get_child("b");
for( const auto& kv : b ){
    cout << "b_b_a = " << kv.second.get<string>("b_b.b_b_a") << "\n";    
}

      



Live demo at Coliru.

I also added some code to print the entire tree recursively so you can see how the JSON is translated to ptree. Array elements are stored as key / value pairs, where the key is an empty string.

+1


source







All Articles