如何使用 Boost.PropertyTree 从以数组为根节点的 JSON 中获取数据?
[
{
"ID": "cc7c3e83-9b94-4fb2-aaa3-9da458c976f7",
"Type": "VM"
}
]
最佳答案
数组元素只是带有属性树名为“”的键的值:
for (auto& array_element : pt) {
for (auto& property : array_element.second) {
std::cout << property.first << " = " << property.second.get_value<std::string>() << "\n";
}
}
打印
ID = cc7c3e83-9b94-4fb2-aaa3-9da458c976f7
Type = VM
#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";
}
}
}
关于c++ - 如何使用 boost::property_tree 解析带根数组的 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26937016/