天天看點

boost property_tree 解析json檔案

boost property_tree解析json檔案相關文檔如下:json_parser 、basic_ptree

  • json_parser:
    • read_json(filename, ptree):用于将filename檔案中的内容讀入ptree結構中。
    • write_json(filename, ptree):用于将ptree結構中的内容寫入filename中。
  • basic_ptree:
    • self_type& get_child(path_type):
    • get_value<>:
  1. 讀取json檔案

json檔案如下:

{
    "rate":{
        "linktype":[0.8, 1.0, 1.0, 0.7, 0.4, 0.7, 0.8, 0.8, 0.9, 0.9, 0.4, 0.8, 1.0],
        "width":[[0.6, 0.8],
                 [0.7, 0.87],
                 [1.0, 1.2],
                 [1.2, 1.4],
                 [1.0, 1.0]],
        "use_toll":[0.33, 1.2]
    },
    "turn_cost":{
        "uturn":{
            "Hturn":0,
            "triangle":1200,
            "normal":[1200, 300, 60, 5]
        }
    }
}
           

讀取json檔案:

#include <iostream>

#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <boost/foreach.hpp>

using namespace std;

int main()
{
    boost::property_tree::ptree pt;
    boost::property_tree::json_parser::read_json("test.json", pt);

    boost::property_tree::ptree child_linktype = pt.get_child("rate.linktype");
	
    BOOST_FOREACH(boost::property_tree::ptree::value_type &vt, child_linktype) {
        cout << vt.second.get_value<double>() << "\t";
    }
    cout << endl;

    return 0;
}
           

輸出結果:

0.8	1	1	0.7	0.4	0.7	0.8	0.8	0.9	0.9	0.4	0.8	1