使用Boost property_tree读取JSON [英] Reading JSON with Boost property_tree

查看:459
本文介绍了使用Boost property_tree读取JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Boost的property tree解析JSON文件.这是JSON文件

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
}

和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");
}

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

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.

我愿意使用其他最佳的库.但是到目前为止,Boost在我看来还是很有前途的.

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

推荐答案

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

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";    
}

在Coliru进行的实时演示.

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

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.

这篇关于使用Boost property_tree读取JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆