C ++:Beautify提升ptree json_parser

时间:2017-08-03 14:55:10

标签: c++ json boost boost-propertytree ptree

在下面的代码中使用C ++ Boost属性树,我期待一个漂亮的输出,如

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

虽然实际上我收到了:

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

是否有任何内置方法可以美化此json结果?

#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;
}

1 个答案:

答案 0 :(得分:1)

您是否尝试将pretty传递给write_json(buf, root, true); 参数?

SET GLOBAL sql_mode=''