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

Parse elements from array in json file using boost

本文关键字:数组 元素 文件 boost 解析 json 使用      更新时间:2023-10-16

我有一个看起来像这样的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>() << " ";
      }
  }
 }

只是为了打印每个变量,但我只处理将它们作为一个集合,而不是每个变量。有人知道如何做到这一点吗?

提前感谢!

对于 JSON 数组,数据节点包含多个名称为空的子节点(文档:c++ 如何使用 boost xml 解析器读取 XML 并存储在 map 中)。

因此,您只需遍历子节点(可选地检查键 == ")。

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

住在科里鲁

#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