Creating JSON arrays in Boost using Property Trees

Simple Array: #include <boost/property_tree/ptree.hpp> using boost::property_tree::ptree; ptree pt; ptree children; ptree child1, child2, child3; child1.put(“”, 1); child2.put(“”, 2); child3.put(“”, 3); children.push_back(std::make_pair(“”, child1)); children.push_back(std::make_pair(“”, child2)); children.push_back(std::make_pair(“”, child3)); pt.add_child(“MyArray”, children); write_json(“test1.json”, pt); results in: { “MyArray”: [ “1”, “2”, “3” ] } Array over Objects: ptree pt; ptree children; ptree child1, child2, child3; child1.put(“childkeyA”, 1); child1.put(“childkeyB”, 2); … Read more

boost::property_tree XML pretty printing

The solution was to add the trim_whitespace flag to the call to read_xml: #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/xml_parser.hpp> int main( void ) { // Create an empty property tree object using boost::property_tree::ptree; ptree pt; // reading file.xml read_xml(“file.xml”, pt, boost::property_tree::xml_parser::trim_whitespace ); // writing the unchanged ptree in file2.xml boost::property_tree::xml_writer_settings<char> settings(‘\t’, 1); write_xml(“file2.xml”, pt, std::locale(), settings); return … Read more

Why does Boost property tree write_json save everything as string? Is it possible to change that?

Ok, I’ve solved it like this, (of course it won’t suite for everybody, as it is a bit of a hack, that need further work). I’ve wrote my own write_json function (simply copied the files, json_parser.hpp and json_parser_write.hpp to my project) and modified the following lines in json_parser_write.hpp: commented line 37 – escaping the quote … Read more

Serializing and deserializing JSON with Boost

Note that property_tree interprets the keys as paths, e.g. putting the pair “a.b”=”z” will create an {“a”:{“b”:”z”}} JSON, not an {“a.b”:”z”}. Otherwise, using property_tree is trivial. Here is a little example. #include <sstream> #include <map> #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/json_parser.hpp> using boost::property_tree::ptree; using boost::property_tree::read_json; using boost::property_tree::write_json; void example() { // Write json. ptree pt; pt.put (“foo”, … Read more