[英]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
。 考慮使用將樹節點解析為struct { int first,second, third; }
的翻譯器或“ parse”函數struct { int first,second, third; }
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.