ar2015
ar2015

Reputation: 6150

C++: Beautify boost ptree json_parser

In the following code using C++ Boost property tree, I expect a beautiful output such as

{
  "fruit": {
    "apple": "true",
    "orange": "true"
  },
  "animal": {
    "cat": "true",
    "dog": "true",
    "bird": {
      "duck": "true"
    }
  }
}

while in reality I receive:

{"fruit":{"apple":"true","orange":"true"},"animal":
{"cat":"true","dog":"true","bird":{"duck":"true"}}}

Is there any built-in method to beautify this json result?

#include <iostream>
#include <string>
#include <sstream>

#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>

using boost::property_tree::ptree;
using boost::property_tree::basic_ptree;


int main()
{
    ptree root;

    root.put("fruit.apple", "true");
    root.put("fruit.orange", "true");
    root.put("animal.cat", "true");
    root.put("animal.dog", "true");
    root.put("animal.bird.duck", "true");

    std::ostringstream buf;
    write_json(buf, root, false);
    buf << std::endl;

    std::string json = buf.str();
    std::cout<<json<<std::endl;

    return 0;
}

Upvotes: 0

Views: 938

Answers (1)

sehe
sehe

Reputation: 393447

Have you tried passing true for the pretty parameter?

write_json(buf, root, true);

Upvotes: 1

Related Questions