This page collects some boost::property_tree code snippet I used
in my software. I hope will be useful to everyone.
#include <boost/property_tree/json_parser.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/foreach.hpp>
boost::property_tree::ptree root;
try {
boost::property_tree::read_json(fileName, root);
}
catch(std::exception & e)
{
}
int version = tree.get<int>("version",1); // get a value (int) from a node with a default if node not exists
int version = tree.get<int>("version"); // get a value (int) and if does not exist throw an exception
std::string type = tree.get<std::string>("type"); // get a value (string) without default (throw an exception)
BOOST_FOREACH(const boost::property_tree::ptree::value_type &v,
root.get_child("node"))
{
// do something with v (see below)
}
boost::property_tree::ptree::const_assoc_iterator i_pts = parent.find("points");
if(parent.not_found() != i_pts) {
const boost::property_tree::ptree & pts = (*i_pts).second;
}
if(!node.empty())
{
// do something
}
// tree is a boost::property_tree::ptree
BOOST_FOREACH( boost::property_tree::ptree::value_type const&v, tree ) {
// v.first is the key
if(v.second.empty()) {
// normal key:value
// use subtree.data() as string value or subtree.get_value<T>()
} else {
// subtree
// use v.second as child
}
}
// iterate on children (example array)
BOOST_FOREACH( boost::property_tree::ptree::value_type const&v, tree.get_child("children") ) {
const std::string & key = v.first; // key
const boost::property_tree::ptree & subtree = v.second; // value (or a subnode)
if(subtree.empty()) {
// This is a key:value
// use subtree.data() as string value or subtree.get_value<T>()
} else {
// This is a subtree
// use subtree as child
}
}
// or without BOOST_FOREACH
for(boost::property_tree::ptree::const_iterator v = tree.begin(); v != tree.end(); ++v) {
float value = v->second.get_value<float>();
}
tree.put("name", value);
tree.put<int>("version", 1);
tree.add("path", "value1");
tree.add("path", "value2");
In JSON this code does not create a "vector"
boost::property_tree::ptree elem;
// fill elem
ptree_parent.push_back( std::make_pair("key", elem ) );
boost::property_tree::write_json(out, root);
[ Back to home ]