如何在Modern C++的nlohmann JSON中迭代对象并修正代码错误
问题分析与修正
首先咱们拆解下你遇到的错误:
你写it["Name"]时编译器报错,核心原因是nlohmann/json的迭代器operator[]是用来按整数索引访问数组元素的,而非访问JSON对象的字符串键。当你遍历的是JSON对象(键值对结构)时,迭代器指向的是std::pair<const std::string, json>类型的元素,直接给[]传字符串键会触发类型不匹配的错误。
修正方案
这里有两种常用的正确访问方式,同时还要解决字符串拼接的隐藏问题:
方式1:通过迭代器的second成员访问子对象
迭代器指向的是键值对,it->first是对象的键(比如"1"、"2"),it->second就是对应的子JSON对象,之后就能正常用["Name"]访问字段了:
#include <iostream> #include <nlohmann/json.hpp> using json = nlohmann::json; void bla(std::string a) { std::cout << a << '\n'; } int main() { json RecentFiles; RecentFiles["1"]["Name"] = "test1.txt"; RecentFiles["1"]["Last modified"] = "monday"; RecentFiles["1"]["Score"] = 5.0f; RecentFiles["2"]["Name"] = "test2.txt"; RecentFiles["2"]["Last modified"] = "tuesday"; RecentFiles["2"]["Score"] = 5.0f; for (auto it = RecentFiles.begin(); it != RecentFiles.end(); ++it) { // 先将JSON字段转成std::string,再和前面的字符串拼接 std::string fileName = it->second["Name"].get<std::string>(); bla("JSON: Recent file = " + fileName); } std::cout << RecentFiles << '\n'; return 0; }
方式2:用迭代器的value()方法获取子对象
it.value()会直接返回迭代器指向的JSON值(也就是子对象),用法和上面类似:
for (auto it = RecentFiles.begin(); it != RecentFiles.end(); ++it) { std::string fileName = it.value()["Name"].get<std::string>(); bla("JSON: Recent file = " + fileName); }
额外注意点
你原代码里还有个隐藏坑:"JSON: Recent file = " + it.value()["Name"]无法直接编译,因为it.value()["Name"]是json类型,不能直接和std::string做加法。必须用get<std::string>()或者直接转成std::string类型才行。
如果只是想快速输出,也可以简化成:
bla("JSON: Recent file = " + std::string(it->second["Name"]));
内容的提问来源于stack exchange,提问作者mnr
相关产品推荐
相关产品推荐

