3
我试图使用Boost的property tree
来解析JSON文件。这里是JSON文件使用Boost读取JSON property_tree
{
"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");
}
问题我现在知道如何阅读最外面的变量a
和c
。但是,我很难读取其他级别,如b_a, b_b_a, b_d_a
等。我如何用Boost来做到这一点?我不一定要寻找一个涉及循环的解决方案,只是试图弄清楚如何“提取”内部变量。
我很乐意使用其他库,如果他们是最佳的。但是到目前为止,Boost看起来对我很有希望。
您可以使用“。”分隔符来指定路径到嵌套节点,比如'jsontree.get(“b.b_b.b_b_a”)' –
zett42
对于JSON,我通常会推荐两种可能性之一。如果你像REST服务器那样需要以尽可能快的速度对大量JSON进行操作,那么你需要[RapidJSON](https://github.com/miloyip/rapidjson)。几乎所有的事情,你可能都想要[Nlohmann的JSON库](https://github.com/nlohmann/json)。 –
@ zett42我试过了,我收到一个错误:'抛出'boost :: exception_detail :: clone_impl>实例后终止调用' ():没有这样的节点(b.b_b.b_b_a)' –
BillyJean