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?

Jan Deinhard
  • 19,645
  • 24
  • 81
  • 137

1 Answers1

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);
Yakov Galka
  • 70,775
  • 16
  • 139
  • 220
  • 2
    Note that a sad corollary to this is that there is no way to create an empty JSON array. – Michael Anderson Sep 01 '12 at 09:02
  • 4
    @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`. – Yakov Galka Sep 01 '12 at 09:06
  • @ybungalobill: which libraries would you recommend? – Jonathan Mar 05 '13 at 19:07
  • @Jonathan [pugixml](http://pugixml.org/) is my favorite for XML. For JSON I had no chance to compare enough libraries to do any meaningful recommendations. – Yakov Galka Mar 05 '13 at 23:05
  • 5
    This doesn't work: error C2664: 'boost::property_tree::basic_ptree::push_back' : cannot convert parameter 1 from 'std::pair<_Ty1,_Ty2>' to 'const std::pair<_Ty1,_Ty2> &' – kovarex Mar 24 '13 at 15:40
  • 2
    @Marwin It doesn't work for me in boost 1.51. However, array.put("", "bar"); seems to work just fine. – Jonathan Apr 17 '13 at 04:46
  • 1
    This does not work for an array of length 1 (at least with boost 1.42). It will get serialized as a string. – flyx Jul 19 '13 at 12:58
  • 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); – Jesus Fernandez Nov 20 '13 at 11:53