使用 boost 解析 json 文件中数组中的元素
Parse elements from array in json file using 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>() << " ";
}
}
}
只是为了打印每个变量,但我只处理将它们作为一个集合,而不是每个变量。有人知道如何做到这一点吗?
提前感谢!
对于 JSON 数组,数据节点包含多个名称为空的子节点(文档:c++ 如何使用 boost xml 解析器读取 XML 并存储在 map 中)。
因此,您只需遍历子节点(可选地检查键 == ")。
这是我的简单列表示例。我使用了一个带有数组的技巧将元素映射到局部变量one
、two
、three
。考虑使用转换器或"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
相关文章:
- 数组元素打印的递归方法
- 如何将字节数组元素替换为修改的十六进制 ASCII 符号?
- 为什么使用数组元素查找最大数字的程序不起作用?
- 数组元素更改值?
- 如何访问宏中定义的数组元素
- 将数组元素递增 1
- C++函数,它将数组、谓词和运算符作为参数,并将运算符应用于满足谓词的数组元素
- 存储指向动态数组元素的指针
- C++通过别名指针以静默方式将错误的类型分配给数组元素
- 在 std::map 中插入数组元素
- 使用指针访问数组元素时出现意外结果
- c++ 使用动态分配运算符反向数组元素
- 为什么在 c++ 中分配 char 数组元素时,分配的字符会被销毁?
- 缺少数组元素问题
- 如何在类中制作 2D 数组元素,然后在其构造函数中指定其维度?
- 创建一个函数来转换数组元素的类型并返回数组的地址
- 删除在结构 c++ 中声明的数组元素
- Getter 和 Setter 用于类 C++ 中的数组元素
- 尝试递归获取数组元素的总和
- 使用SWIG将numpy数组元素(int)传递给c++int