c++,使用nlohmann::json解析JSON数组

标签 c++ json nlohmann-json

在导入到我的 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 我假设 j["ec"].begin() 不正确。

我应该怎么做,谢谢。

最佳答案

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

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

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

(live demo)

关于c++,使用nlohmann::json解析JSON数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53324659/

相关文章:

引用类型转换中的 C++ 虚函数

java - 需要将下面的 JSON 对象转换为 String JAVA

json - Angular 6 - 解析 JSON

c++ - 使用 "JSON for Modern C++"库检测整数不适合指定类型?

c++ - 使用 nlohmann json 在 C++ 中创建嵌套的 json 对象

c++ - 尝试显示纹理但仅使用 OpenGL 获得纯色

c++ - 使用 gdb 在 C++ 中跟踪函数调用

python - 从 C++ 自动生成 python 模块的 Tensorflow 源代码

json - Swift 解码具有混合类型和可能的子结构的 JSON

C++,JSON,获取数组中的对象成员