Renato Garcia

Boost Property Tree Extensions

Inside a bigger project, I'm using the Boost Property Tree library to read the config files and pass it to the classes. For this reason, I have made any extensions to Boost Property Tree.

Bellow I will describe the main extensions, and all code can be found here.

Assign

Suppose that in C++ code you wish to create a boost::ptree as:

key1 value1
key2
{
    key3 12345
    {
        key4 "value4 with spaces"
    }
    key5 value5
    "" 10
    "" 11
    "" 12
}
Text only

Using only the boost::basic_ptree class methods, the code would be something like:

ptree pt;
pt.add("key1", "value1");

ptree tmpPt1;
tmpPt1.add("key3", 12345);

ptree tmpPt2;
tmpPt2.add("key4", "value4 with spaces");

tmpPt1.push_back(std::make_pair("", tmpPt2));
tmpPt1.add("key5", "value5");

ptree tmpPt3;
tmpPt3.put_value(10);
tmpPt1.push_back(std::make_pair("", tmpPt3));

ptree tmpPt4;
tmpPt4.put_value(11);
tmpPt1.push_back(std::make_pair("", tmpPt4));

ptree tmpPt5;
tmpPt5.put_value(12);
tmpPt1.push_back(std::make_pair("", tmpPt5));

pt.add_child("key2", tmpPt1);
C++

A bit verbose. One nice alternative would be to use something similar to the Boost Assign library, and is precisely this what this extension do. Using the tree class, that same boost::ptree can be build with the code:

ptree pt =
    tree()
    ("key1", "value1")
    ("key2", tree()
        ("key3", 12345)
        (tree()
            ("key4", "value4 with spaces"))
        ("key5", "value5")
        (10)(11)(12));
C++

Lua parser

If the config files become complexes, write it as a Lua script can significantly easily the work. This extension allows that a Lua script be used to build a boost::ptree. The aim is that the Lua's code:

function func(w)
    return "hello " .. w
end

root = {
    array = { 10, 11, 12, 13, 14, 15,},
    hi = func("world"),
    subtree = {
        one = 1,
        two = 2,
    },
}
Lua

Can be executed and loaded as a boost::ptree with:

ptree pt;
read_lua("test.lua", "root", pt);
C++

Python API

The project into what these extensions was created have a Python binding, and almost all classes accept a boost::ptree in the constructor. Thus was needed to create a Python binding to Boost Property Tree library too.

If you is using the SWIG to expose your classes to Python, the ptree.i file will make transparent the Python -> C++ ptree translation. Else, the binding code don't uses the SWIG anyway and a ptree can be created and used in Python just as:

pt1 = (tree()
         ('key1', 1)
         ('key2', 2)
         ('subtree', tree()(1)(2)(3))
     ).ptree
pt2 = read_json('tree.json')
pt1.add('aaa', 'bbb')
print pt1
Python