How to output boost property tree as JSON encoded string?

Fernando picture Fernando · Apr 26, 2016 · Viewed 9.1k times · Source

Sometimes it is very useful to create JSON encoded strings for representing and exchanging data. What is be best way of encoding a Boost property tree into a JSON string?

Answer

Fernando picture Fernando · Apr 26, 2016

Here is a sample code for doing that task:

#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <boost/optional.hpp>
#include <iostream>
#include <sstream>
#include <cstdlib>

int main()
{
    boost::property_tree::ptree pt;
    pt.put("Test", "string");
    pt.put("Test2.inner0", "string2");
    pt.put("Test2.inner1", "string3");
    pt.put("Test2.inner2", 1234);

    std::stringstream ss;
    boost::property_tree::json_parser::write_json(ss, pt);

    std::cout << ss.str() << std::endl;

    return 0;
}

To compile this code with GCC:

g++ main.cpp -lboost_system -o SamplePT_JSON

And here is the expected output:

{
    "Test": "string",
    "Test2":
    {
        "inner0": "string2",
        "inner1": "string3",
        "inner2": "1234"
    }
}