简体   繁体   中英

C++: How to create an array using boost::property_tree?

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

#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?

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM