Boost Ptree Code Example

This page collects some boost::property_tree code snippet I used in my software. I hope will be useful to everyone.

Include Headers

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

Read a JSON file in a PTREE

boost::property_tree::ptree root;
try {
boost::property_tree::read_json(fileName, root);
}
catch(std::exception & e)
{
}

Get a value from a ptree node

 int version = tree.get<int>("version",1);	// get with a default
std::string type = tree.get<std::string>("type"); // get without default (throw an exception)

Iterate on children of a node (for example a vector)

BOOST_FOREACH(const boost::property_tree::ptree::value_type &v,
                          root.get_child("node"))
   {
// do something with v (see below)
}

Search for a node

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;
}

Test if a node have children

if(!node.empty())
{
// do something
}

Iterate on any children of a node

BOOST_FOREACH(  boost::property_tree::ptree::value_type const&v, tree ) {
// v.first is the key
if(v.second.empty())
{
// normal key:value
// use v.second.data() as string value
}
else
{
// subtree
// use v.second as child
}
}
less functional solution:
BOOST_FOREACH(  boost::property_tree::ptree::value_type const&v, parent.get_child("") ) {
boost::property_tree::ptree key = v.first;
boost::property_tree::ptree subtree = v.second;
std::string nodestr =
parent.get<std::string>(v.first); // NO: use v.second.data()
}

Iterate on a vector

for(boost::property_tree::ptree::const_iterator q = v.begin(); q !=v.end(); ++q) {
float value = q->second.get_value<float>();
}

Add or replace an unique element to a property vector

tree.put("name", value);
tree.put<int>("version", 1);

Add a treenode to a property tree

boost::property_tree::ptree elem;
// fill elem
ptree_parent.push_back( std::make_pair("key", elem ) );

Add an element to a property vector

boost::property_tree::ptree elem;
// fill elem
ptree_parent.push_back( std::make_pair("", elem ) );
ptree_parent.add_child( "key", elem );

Add or replace an element in a property tree

ptree_parent.put_child("name", elem);

Write a JSON

boost::property_tree::write_json(out, root);

[ Back to home ]