I have some JSON with a handful of integer array variables, like so:
{\"a\": [8, 6, 2], \"b\": [2, 2, 1]}
I would like to use boost propert
JSON support, is spotty with boost property tree.
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.
(from the documentation)
You can iterate the array with a helper function.
#include
#include
using boost::property_tree::ptree;
template
std::vector as_vector(ptree const& pt, ptree::key_type const& key)
{
std::vector r;
for (auto& item : pt.get_child(key))
r.push_back(item.second.get_value());
return r;
}
int main()
{
std::stringstream ss("{\"a\": [8, 6, 2], \"b\": [2, 2, 1]}");
ptree pt;
read_json(ss, pt);
for (auto i : as_vector(pt, "a")) std::cout << i << ' ';
std::cout << '\n';
for (auto i : as_vector(pt, "b")) std::cout << i << ' ';
}
See it Live On Coliru. Output:
8 6 2
2 2 1