I need to add unnamed nodes to a boost::property_tree::ptree just like it's JSON parser does for arrays. However when I want to do it I get such assertion during runtime:
Assertion failed: !p.empty() && "Empty path not allowed for put_child.", file C:\Program Files\Boost\boost\include/boost/property_tree/detail/ptree_implementation.hpp, line 877
I do it like
tree.add_child(name, child);
where tree and child are both ptree-s and name char*.
How could I do it like the JSON parser for ptree-s does?
I don't think Boost.Property_tree has a good reason for disallowing empty paths in add_child
or put_child
. The way root detection is implemented in their internal path utilities requires non-empty paths.
You can get around this by not using their pathing utilities when adding array elements.
using boost::property_tree::ptree;
ptree pt;
pt.put_child( "path.to.array", ptree() );
auto& array = pt.get_child( "path.to.array" );
array.push_back( std::make_pair( "", ptree("foo") ) );
array.push_back( std::make_pair( "", ptree("bar") ) );
boost::property_tree::json_parser::write_json( std::cout, pt, false );
// {"path":{"to":{"array":["foo","bar"]}}}