C++ nonlohmann json读取子对象

标签 c++ json nlohmann-json

我实际上正在开发一个小程序,我需要读取一个 json 文件。 我正在使用 C++ 和 nlohmann json 库。

我当前的代码

int main(int argc, const char** argv){
    ifstream ifs("Myjson.json");
    json j = json::parse(ifs);
    cout << "Front image path : "<< j["front"]["imagePath"]  << "\n";
    cout << "Back image path : " << j["back"]["imagePath"] << "\n";

    system("PAUSE");
    return 0;
}

MyJson.json

{
    "Side": [
        {
            "camera": "22344506",
            "width": 19860,
            "nbParts": 662,
            "wParts": 30,
            "height": 1600,
            "imagePath": "./Tchek_buffer/22344506.png"
        },
        {
            "camera": "22344509",
            "width": 5296,
            "nbParts": 662,
            "wParts": 8,
            "height": 1600,
            "imagePath": "./Tchek_buffer/22344509.png"
        },
    ],
    "front": {
        "camera": "22344513",
        "image": null,
        "width": 1200,
        "height": 1600,
        "imagePath": "./Tchek_buffer/22344513.png"
    },
    "back": {
        "camera": "22344507",
        "image": null,
        "width": 1600,
        "height": 1200,
        "imagePath": "./Tchek_buffer/22344507.png"
    },
}

我可以轻松读取和显示“背面”和“正面”对象,但无法读取扫描仪对象。 我想获取所有“扫描仪”对象的“imagePath”

我试过类似的东西

cout << "scanner image path : " << j["scanner"]["imagePath"] << "\n";
cout << "scanner image path : " << j["scanner[1]"]["imagePath"] << "\n";
cout << "scanner image path : " << j["scanner"[1]]["imagePath"] << "\n";

我只得到“空”结果

如果有人可以帮助我并向我解释如何让它发挥作用。

最佳答案

假设 scanner 实际上是 json 中的 Side

您的试验执行了以下操作:

  • 访问列表的“imagePath”属性
  • 访问列表的“scanner[1]”属性
  • 访问列表的“c”(第二个字符)属性。

所以肮脏的方法是:

cout << "scanner image path : " << j["Side"][0]["imagePath"] << "\n";
cout << "scanner image path : " << j["Side"][1]["imagePath"] << "\n";

正确的应该是:

for (auto& element : j["Side"])
  cout << "scanner image path : " << element["imagePath"] << "\n";

关于C++ nonlohmann json读取子对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46317907/

相关文章:

c++ - 制作 GUI 时清理 OOP 设计

javascript - Yeoman Generator - 如何解析 Generator 项目的 Package.json

javascript - JSON.stringify 在不同的 URL 上给出不同的结果

c++ - 将 json 文件转换为 json 对象会打乱对象的顺序

Mat的C++代码转换

python - 检测接近的物体

c++ - 设置/删除窗口子类时正确传递/删除数据

c# - 使用 WebHttpBinding 通过 HTTP 从 SQL 传输表格数据的绝对最快方法

c++ - 如何在 JSON 中创建文件层次结构表示

c++ - 在数组C++中读取数组内部的项目