Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to output boost property tree as JSON encoded string?

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?

like image 403
Fernando Avatar asked Apr 26 '16 14:04

Fernando


Video Answer


1 Answers

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"
    }
}
like image 71
Fernando Avatar answered Nov 15 '22 02:11

Fernando