如何使用boost :: property_tree解析具有数组根的JSON [英] How to use boost::property_tree to parse JSON with array root

查看:154
本文介绍了如何使用boost :: property_tree解析具有数组根的JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何通过使用Boost.PropertyTree从以数组为根节点的JSON中获取数据?

How can I get data from JSON with array as root node by using Boost.PropertyTree?

[
  {
      "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";
    }
}

打印

ID = cc7c3e83-9b94-4fb2-aaa3-9da458c976f7
Type = VM


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

这篇关于如何使用boost :: property_tree解析具有数组根的JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆