サンプルの動作確認バージョン [GCC4.4/1.42.0] [VC9/1.42.0]
#include <iostream>
#include <string>
#include <boost/foreach.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
using namespace std;
int main()
{
// JSON読み込み
boost::property_tree::ptree t;
read_json("example.json", t);
// Image.Width を表示
cout << t.get<int>("Image.Width") << endl;
// Image.Thumbnail.Url を表示
cout << t.get<string>("Image.Thumbnail.Url") << endl;
// Image.IDs ノードを取得
boost::property_tree::ptree& id = t.get_child("Image.IDs");
BOOST_FOREACH(const boost::property_tree::ptree::value_type& e,id) // 子供を順番に表示
cout << e.second.data() << endl;
// 編集
t.put("Image.Width", 1200);
t.put("Image.Height", 960);
t.add("Memo", "Modified!!");
// cout へ出力
cout << "--------" << endl;
write_json(cout, t);
}
// http://www.ietf.org/rfc/rfc4627.txt
{
"Image": {
"Width": 800,
"Height": 600,
"Title": "View from 15th Floor",
"Thumbnail": {
"Url": "http://www.example.com/image/481989943",
"Height": 125,
"Width": "100"
},
"IDs": [116, 943, 234, 38793]
}
}
800
http://www.example.com/image/481989943
116
943
234
38793
--------
{
"Image":
{
"Width": "1200",
"Height": "960",
"Title": "View from 15th Floor",
"Thumbnail":
{
"Url": "http://www.example.com/image/481989943",
"Height": "125",
"Width": "100"
},
"IDs":
[
"116",
"943",
"234",
"38793"
]
},
"Memo": "Modified!!"
}
XML や JSON などのツリー構造のアプリケーション設定データを扱うためのライブラリです。 使い方は簡単で、上記のサンプルにあるように、read_xxx/write_xxx で ptree オブジェクトにファイル等から読み書きして、 get, get_child, put, add でデータを読んだり書いたりします。 削除は erase です。