2017-05-01 73 views
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"); 
} 

问题我现在知道如何阅读最外面的变量ac。但是,我很难读取其他级别,如b_a, b_b_a, b_d_a等。我如何用Boost来做到这一点?我不一定要寻找一个涉及循环的解决方案,只是试图弄清楚如何“提取”内部变量。

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

+0

您可以使用“。”分隔符来指定路径到嵌套节点,比如'jsontree.get (“b.b_b.b_b_a”)' – zett42

+1

对于JSON,我通常会推荐两种可能性之一。如果你像REST服务器那样需要以尽可能快的速度对大量JSON进行操作,那么你需要[RapidJSON](https://github.com/miloyip/rapidjson)。几乎所有的事情,你可能都想要[Nlohmann的JSON库](https://github.com/nlohmann/json)。 –

+0

@ zett42我试过了,我收到一个错误:'抛出'boost :: exception_detail :: clone_impl >实例后终止调用' ():没有这样的节点(b.b_b.b_b_a)' – BillyJean

回答

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中。数组元素被存储为键/值对,其中键是空字符串。

相关问题