使用boost从json文件中解析数组中的元素

时间:2016-02-25 17:34:04

标签: c++ arrays json boost

我有一个如下所示的json文件:

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

在数据中,每个数组都有意义所以我需要为每个数组分配一个变量(在循环中),如:

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

我正在做这样的事情(我在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>() << " ";
      }
  }
 }

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

提前感谢!

1 个答案:

答案 0 :(得分:2)

对于JSON数组,数据节点包含多个空名称的子节点(docs:c++ How to read XML using boost xml parser and store in map)。

所以你只需遍历子节点(可选择检查键==&#34;&#34;)。

这是我的简单例子。我使用数组技巧将元素映射到局部变量onetwothree。考虑使用翻译或解析&#34;将树节点解析为struct { int first,second, third; }的函数(例如https://stackoverflow.com/a/35318635/85371

<强> Live On 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