简体   繁体   English

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

[英]How to use boost::property_tree to parse JSON with array root

How can I get data from JSON with array as root node by using Boost.PropertyTree? 如何通过使用Boost.PropertyTree从阵列作为根节点获取JSON数据?

[
  {
      "ID": "cc7c3e83-9b94-4fb2-aaa3-9da458c976f7",
      "Type": "VM"
  }
]

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 住在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";
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM