如何使用 boost::property_tree 解析带有数组根的 JSON

2023-12-15

如何使用 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";
    }
}

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";
        }
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 boost::property_tree 解析带有数组根的 JSON 的相关文章

随机推荐