BillyJean
BillyJean

Reputation: 1587

Reading JSON with Boost property_tree

I'm trying to use Boost's 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 a 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 the outermost variables a and c. However, I'm having difficulty reading other levels such as 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 solution involving loops, merely trying to figure out how to "extract" inner variables.

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

Upvotes: 6

Views: 12379

Answers (1)

zett42
zett42

Reputation: 27756

To get nested elements you can use the path syntax where each path component is separated by ".". Things are a little bit more complicated here because the child node b is an array. So you can't 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've also added code to print the whole tree recursively so you can see how the JSON gets translated to the ptree. Arrays elements are stored as key/value pairs where the key is an empty string.

Upvotes: 5

Related Questions