【问题标题】:c++, JSON array parsing using nlohmann::jsonc++,使用 nlohmann::json 解析 JSON 数组
【发布时间】:2018-11-15 17:11:21
【问题描述】:

在导入到我的 c++ 程序中的 json 文件中,结构如下:

{
 "a":"1",
 "ec":[
       {
        "a":"0x00",
        "s":[
             {"a":"0xA0"},
             {"a":"0xA1"},
            ],
        "b":"v1"
       },
       {
        "a":"0x01",
        "s":[
             {"a":"0xB0"},
             {"a":"0xB1"},
            ],
        "b":"v2"
       }
      ]
}

我想遍历 "ec" 数组并获取所有 "a" 的值,并且每个 "a" 的 s 数组的值都相同

vector<string> ec_a; // should contain {"0x00","0x01"}
vector<string> a1_s; // should contain {"0xA0", "0xA1"}
vector<string> a2_s; // should contain {"0xB0","0xB1"}

首先我得到了ec 的大小,但是从docs 我知道应该使用迭代器来完成其余的操作

int n=j["ec"].size() // n = 2
for(auto it=j["ec"].begin();it!=j["ec"].end();++it){
  if(it.key() == "a") ec_a.push_back(it.value());
}

但是得到这个异常nlohmann::detail::invalid_iterator at memory location 我认为j["ec"].begin() 是不正确的。

我该怎么做呢,谢谢。

【问题讨论】:

    标签: c++ json nlohmann-json


    【解决方案1】:

    it 是复合类型的迭代器。复合类型本身没有“键”。

    您想要实现的目标比您想象的要容易得多。你可以试试这个:

    std::vector<std::string> ec_a;
    for (auto& elem : j["ec"])
        ec_a.push_back(elem["a"]);
    

    (live demo)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多