c++:如何使用boost::property_tree创建数组?

时间:2022-09-23 21:00:28

I don't see a way to create an array using boost::property tree. The following code ...

我没有看到使用boost::property树创建数组的方法。下面的代码…

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

#include <iostream>

int main()
{
  try {
    boost::property_tree::ptree props;
    props.push_back(std::make_pair("foo", "bar"));
    props.push_back(std::make_pair("foo", "baz"));
    boost::property_tree::write_json("prob.json", props);
  } catch (const std::exception & ex) {
    std::cout << ex.what() << std::endl;
  }
}

... just gives me ...

…只是给了我…

{
  "foo": "bar",
  "foo": "baz"
}

The docs on boost::property_tree are sparse. How do I create an JSON array with boost::property_tree?

boost: property_tree上的文档是稀疏的。如何使用boost::property_tree创建JSON数组?

1 个解决方案

#1


20  

If you have a sub-tree whose only nodes have empty keys, then it will be serialized as an array:

如果有一个子树,它的唯一节点有空键,那么它将被序列化为一个数组:

boost::property_tree::ptree array;
array.push_back(std::make_pair("", "bar"));
array.push_back(std::make_pair("", "baz"));

boost::property_tree::ptree props;
props.push_back(std::make_pair("array", array));

boost::property_tree::write_json("prob.json", props);

#1


20  

If you have a sub-tree whose only nodes have empty keys, then it will be serialized as an array:

如果有一个子树,它的唯一节点有空键,那么它将被序列化为一个数组:

boost::property_tree::ptree array;
array.push_back(std::make_pair("", "bar"));
array.push_back(std::make_pair("", "baz"));

boost::property_tree::ptree props;
props.push_back(std::make_pair("array", array));

boost::property_tree::write_json("prob.json", props);