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 (and convert the type)

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)

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

// 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>();
}

Add or replace an unique element to a property vector

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

Add multiple element to a property vector

 tree.add("path", "value1");
 tree.add("path", "value2");
In JSON this code does not create a "vector"

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 ]