我实际上正在处理一个小程序,我需要读取一个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"
},
}
我可以轻松阅读并显示&#34;返回&#34;和#34;前面&#34;对象,但我无法读取扫描仪对象。 我想得到&#34; imagePath&#34;所有&#34;扫描仪&#34;对象
我试过像
这样的东西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";
我只得到&#34; null&#34;结果
如果有人可以帮助我并解释我如何使其发挥作用。
答案 0 :(得分:2)
假设json中scanner
实际上是Side
。
您的试验做了以下事项:
所以肮脏的方式是:
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";
答案 1 :(得分:0)
我认为"Side"
和"scanner"
在您的问题中是等效的。你可能在标签之间做了不匹配。
我不知道这个库,但我想它就是这样的:
cout << "scanner image path 1 : " << j["scanner"][0]["imagePath"] << "\n";
cout << "scanner image path 2 : " << j["scanner"][1]["imagePath"] << "\n";
您可以在文档here中找到示例。