我实际上正在开发一个小程序,我需要读取一个 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/