问题
How can I get data from JSON with array as root node by using Boost.PropertyTree?
[
{
"ID": "cc7c3e83-9b94-4fb2-aaa3-9da458c976f7",
"Type": "VM"
}
]
回答1:
The array elements are just values with a key named "" for property tree:
for (auto& array_element : pt) {
for (auto& property : array_element.second) {
std::cout << property.first << " = " << property.second.get_value<std::string>() << "\n";
}
}
Prints
ID = cc7c3e83-9b94-4fb2-aaa3-9da458c976f7
Type = VM
Live On Coliru
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <iostream>
using namespace boost::property_tree;
int main()
{
std::istringstream iss(R"([
{
"ID": "cc7c3e83-9b94-4fb2-aaa3-9da458c976f7",
"Type": "VM"
}
]
)");
ptree pt;
json_parser::read_json(iss, pt);
for (auto& array_element : pt) {
for (auto& property : array_element.second) {
std::cout << property.first << " = " << property.second.get_value<std::string>() << "\n";
}
}
}
来源:https://stackoverflow.com/questions/26937016/how-to-use-boostproperty-tree-to-parse-json-with-array-root