views:

934

answers:

2

I'm trying to create a JSON array using boost property trees.

The documentation says: "JSON arrays are mapped to nodes. Each element is a child node with an empty name."

So I'd like to create a property tree with empty names, then call write_json(...) to get the array out. However, the documentation doesn't tell me how to create unnamed child nodes. I tried ptree.add_child("", value), but this yields:

Assertion `!p.empty() && "Empty path not allowed for put_child."' failed

The documentation doesn't seem to address this point, at least not in any way I can figure out. Can anyone help?

+1  A: 

What you need to do is this piece of fun. This is from memory, but something like this works for me.

boost::property_tree::ptree root;
boost::property_tree::ptree child1;
boost::property_tree::ptree child2;

// .. fill in children here with what you want
// ...

ptree.push_back( std::make_pair("", child1 ) );
ptree.push_back( std::make_pair("", child1 ) );

But watch out there's several bugs in the json parsing and writing. Several of which I've submitted bug reports for - with no response :(

EDIT: to address concern about it serializing incorrectly as {"":"","":""}

This only happens when the array is the root element. The boost ptree writer treats all root elements as objects - never arrays or values. This is caused by the following line in boost/propert_tree/detail/json_parser_writer.hpp

else if (indent > 0 && pt.count(Str()) == pt.size())

Getting rid of the "indent > 0 &&" will allow it to write arrays correctly.

If you don't like how much space is produced you can use the patch I've provided here

Michael Anderson
This isn't right. After dumping to JSON, rather than getting an array, I get this: { "": "", "": "" }.
Chris Stucchio
Updated the post to reflect why this is happening and how to fix it.
Michael Anderson
A: 

When starting to use Property Tree to represent a JSON structure I encountered similar problems which I did not resolve. Also note that from the documentation, the property tree does not fully support type information:

JSON values are mapped to nodes containing the value. However, all type information is lost; numbers, as well as the literals "null", "true" and "false" are simply mapped to their string form.

After learning this, I switched to the more complete JSON implementation JSON Spirit. This library uses Boost Spirit for the JSON grammar implementation and fully supports JSON including arrays.

I suggest you use an alternative C++ JSON implementation. See the Stack Overflow question What’s the best C++ JSON parser? for some alternatives to JSON Spirit.

Yukiko