使用 Boost property_tree 读取 JSON

Bil*_*ean 5 c++ json boost

我正在尝试使用 Boostproperty tree来解析 JSON 文件。这是 JSON 文件

{
    "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
}
Run Code Online (Sandbox Code Playgroud)

和一个 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");
}
Run Code Online (Sandbox Code Playgroud)

问题我目前知道如何读取最外面的变量ac。然而,我在阅读其他级别时遇到困难,例如b_a, b_b_a, b_d_a等等。我怎样才能用Boost做到这一点?我不一定要寻找涉及循环的解决方案,只是想弄清楚如何“提取”内部变量。

如果其他库是最佳的,我愿意使用它们。但到目前为止,Boost 对我来说看起来很有希望。

zet*_*t42 5

要获取嵌套元素,您可以使用路径语法,其中每个路径组件由 分隔"."。这里的事情有点复杂,因为子节点b是一个数组。所以你不能没有循环。

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";    
}
Run Code Online (Sandbox Code Playgroud)

在 Coliru 进行现场演示。

我还添加了递归打印整个树的代码,以便您可以看到 JSON 如何转换为 ptree。数组元素存储为键/值对,其中键是空字符串。