-->

Boost ptree top level array

2019-07-24 16:36发布

问题:

I would like to have write_json output a top level array, something to the effect of:

[{...},{...},{...},...,{...}]

But when I pass a list to write_json, it converts to a json full of blank keys.

{"":{...},"":{...},"":{...},..."":{...}}

Using add_child actually respects the array and gives me the closest thing of:

{"Some Key":[{...},{...},{...},...,{...}]}

But that's still not what I want.

Any idea how to make that array top level?

回答1:

Boost does not have a JSON library (nor does it have an XML library). It has a Property Tree library (which happens to include a JSON compatible representation).

The limitations you run into are perfectly clearly documented right there: http://www.boost.org/doc/libs/1_62_0/doc/html/property_tree/parsers.html#property_tree.parsers.json_parser

The property tree dataset is not typed, and does not support arrays as such. Thus, the following JSON / property tree mapping is used:

  • JSON objects are mapped to nodes. Each property is a child node.
  • JSON arrays are mapped to nodes. Each element is a child node with an empty name. If a node has both named and unnamed child nodes, it cannot be mapped to a JSON representation.
  • 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.
  • Property tree nodes containing both child nodes and data cannot be mapped.
  • JSON round-trips, except for the type information loss.

It goes on to show an example of EXACTLY what you run into.