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

1

16

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?

Chipboard answered 20/9, 2010 at 12:14 Comment(0)
T
21

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);
Tradesfolk answered 20/9, 2010 at 12:59 Comment(8)
Note that a sad corollary to this is that there is no way to create an empty JSON array.Monolayer
@MichaelAnderson: I do not consider using boost::property_tree for manipulating XML and JSON a good idea in the first place. It is not what it was built for. There are much better libraries for both of these tasks, which are also as 'small' as boost::property_tree.Tradesfolk
@ybungalobill: which libraries would you recommend?Democrat
@Democrat pugixml is my favorite for XML. For JSON I had no chance to compare enough libraries to do any meaningful recommendations.Tradesfolk
This doesn't work: error C2664: 'boost::property_tree::basic_ptree<Key,Data>::push_back' : cannot convert parameter 1 from 'std::pair<_Ty1,_Ty2>' to 'const std::pair<_Ty1,_Ty2> &'Peter
@Marwin It doesn't work for me in boost 1.51. However, array.put("", "bar"); seems to work just fine.Democrat
This does not work for an array of length 1 (at least with boost 1.42). It will get serialized as a string.Impressive
For me this snippet is working: Tree array; for(; begin != end; begin++){Tree item;item.put("", *begin); array.push_back(std::make_pair("", item)); } t.add_child(path, array);Impenetrability

© 2022 - 2024 — McMap. All rights reserved.