使用Boost解析json文件中数组中的元素 [英] Parse elements from array in json file using boost

查看:1325
本文介绍了使用Boost解析json文件中数组中的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像这样的json文件:

I have a json file that looks like this:

{
        "type": "2D",
        "data":
        [
            [
                "26",
                "17",
                "1"
            ],
            [
                "13",
                "29",
                "1"
            ],
            [
                "13",
                "30",
                "1"
            ],
....

在数据中,每个数组都有其含义,因此我需要(在循环中)为每个数组分配一个变量,例如:

In data, each array have a meaning so I need to assign a variable to each one (in a loop), like:

int first = 26;
int second = 17;
int third = 1;

我正在做这样的事情(我在v之前定义):

I was doing something like this (I defined before v):

BOOST_FOREACH(boost::property_tree::ptree::value_type &v2, v.second.get_child("data")) {

 BOOST_FOREACH (boost::property_tree::ptree::value_type& itemPair, v2.second) {
  cout << itemPair.second.get_value<std::string>() << " ";
      }
  }
 }

仅打印每个变量,但我只处理将它们作为一个集合,而不是每个变量.有人知道怎么做吗?

Just to print each variable, but I handle only to have them as a set, not each one. Does anyone have an idea how to do it?

提前谢谢!

推荐答案

对于JSON数组,数据节点包含多个空名称的子节点(文档:

For JSON arrays, the data node contains multiple child nodes with empty name (docs: c++ How to read XML using boost xml parser and store in map).

因此,您只需要遍历子节点(可以选择检查键==").

So you would just loop through the child nodes (optionally checking that the key == "").

这是我的简化列表示例.我使用了一个带有数组的技巧,将元素映射到局部变量onetwothree.考虑使用转换程序或将树节点解析为struct { int first,second, third; }的解析"函数(例如, https://stackoverflow.com /a/35318635/85371 )

Here's my simplist example. I used a trick with an array to map elements to the local variables one, two, three. Consider using a translator or a "parse" function that parses a tree node into a struct { int first,second, third; } instead (e.g. https://stackoverflow.com/a/35318635/85371)

在Coliru上直播

#include <boost/property_tree/json_parser.hpp>
#include <iostream>

int main() {
    boost::property_tree::ptree pt;
    read_json("input.txt", pt);

    using namespace std;
    for(auto& array3 : pt.get_child("data")) {
        int first, second, third;
        int* const elements[3] = { &first, &second, &third };
        auto element = begin(elements);

        for (auto& i : array3.second) {
            **element++ = i.second.get_value<int>();

            if (element == end(elements)) break;
        }

        std::cout << "first:" << first << " second:" << second << " third:" << third << "\n";
    }
}

对于输入{"type":"2D","data":[["26","17","1"],["13","29","1"],["13","30","1"]]}打印:

first:26 second:17 third:1
first:13 second:29 third:1
first:13 second:30 third:1

这篇关于使用Boost解析json文件中数组中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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