【问题标题】:Reading JSON with Boost property_tree使用 Boost property_tree 读取 JSON
【发布时间】:2017-05-01 19:34:35
【问题描述】:

我正在尝试使用 Boost 的 property 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
}

和一个 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 做到这一点?我不一定要寻找涉及循环的解决方案,只是想弄清楚如何“提取”内部变量。

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

【问题讨论】:

  • 对于 JSON,我通常会推荐两种可能性之一。如果您正在做类似 REST 服务器之类的事情,需要尽可能快地对 大量 数量的 JSON 进行操作,那么您需要 RapidJSON。对于几乎所有其他内容,您可能需要Nlohmann's JSON library
  • 使用 Nlohmann 的库,检索 b_d_a 将类似于:json j = json::parse(input_string); std::cout &lt;&lt; j["b"]["b_d"]["b_d_a"];
  • 您收到错误是因为我错过了子节点b 是一个数组的事实。看我的回答。
  • @Jerry 我想你需要像j["b"][0]["b_d"][0]["b_d_a"] 这样的东西,因为bb_d 都是数组。我不知道这种语法是否有效。
  • @zett42:哦,完全正确(我没有仔细阅读 JSON)。是的,你写的应该没问题。

标签: c++ json boost


【解决方案1】:

要获取嵌套元素,您可以使用路径语法,其中每个路径组件由"." 分隔。这里的事情有点复杂,因为子节点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";    
}

Live demo at Coliru.

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

【讨论】:

    猜你喜欢
    • 2018-10-18
    • 1970-01-01
    • 1970-01-01
    • 2017-12-27
    • 2018-01-04
    • 2013-09-24
    • 1970-01-01
    • 1970-01-01
    • 2019-02-10
    相关资源
    最近更新 更多