nlohmann/json解析嵌套数组到std::vector需分层访问:先取外层数组,再对每个元素检查字段存在性及类型(如contains()和is_array()),最后对内层字段调用get<std::vector<T>>()或push_back构造。

用 nlohmann/json 解析嵌套数组到 std::vector
直接用 nlohmann::json 的 get<std::vector<T>>() 无法处理嵌套结构——它只适用于扁平、类型一致的数组。比如 JSON [{"id":1,"tags":["a","b"]}] 中的 tags 是嵌套在对象里的字符串数组,不能靠一层 get<std::vector<std::string>>() 拿到。
正确做法是分层访问:先取外层数组,再对每个元素提取字段,最后对该字段调用 get<std::vector<T>>() 或用范围 for + push_back 构造。
示例:
nlohmann::json j = R"([
{"name":"foo", "scores":[95,87,91]},
{"name":"bar", "scores":[88,92]}
])"_json;
std::vector<std::vector<int>> all_scores;
for (const auto& item : j) {
// 确保 scores 字段存在且为数组
if (item.contains("scores") && item["scores"].is_array()) {
all_scores.push_back(item["scores"].get<std::vector<int>>());
}
}
遇到 parse_error 或 type_error 怎么办
常见报错如 [json.exception.type_error.302] type must be array, but is string,说明你试图对非数组值调用 get<std::vector<T>>();而 parse_error.101 多因 JSON 格式非法(比如末尾逗号、单引号)。
立即学习“C++免费学习笔记(深入)”;
安全做法永远加类型检查:
- 用
is_array()判定是否为数组,而非仅靠字段名存在 - 用
is_number_integer()/is_string()验证数组内元素类型(尤其当 JSON 可能混入null或数字/字符串不一致时) - 避免直接写
j["data"][0]["items"].get<std::vector<int>>()——中间任意一级缺失或类型错都会崩溃
更健壮的写法:
Easily find JSON paths within JSON objects using our intuitive Json Path Finder
if (j.is_array()) {
for (size_t i = 0; i < j.size(); ++i) {
const auto& obj = j[i];
if (obj.contains("items") && obj["items"].is_array()) {
std::vector<int> v;
for (const auto& x : obj["items"]) {
if (x.is_number_integer()) v.push_back(x.get<int>());
}
result.push_back(v);
}
}
}
嵌套深度大时,operator[] 链式调用的风险
j["root"]["level1"]["level2"]["values"] 看起来简洁,但只要其中任一 key 不存在或类型不符,就会抛 out_of_range 或 type_error,且无法区分是哪一级出的问题。
建议改用带默认值和类型防护的访问模式:
- 用
value()提供默认 fallback:obj.value("tags", nlohmann::json::array()) - 用
at()替代[]获取更明确的out_of_range异常(便于定位 key 错误) - 对不确定结构,优先用
find()判断键是否存在:if (obj.find("meta") != obj.end() && (*obj.find("meta")).is_object())
性能敏感场景:避免重复解析和隐式拷贝
每次调用 get<std::vector<T>>() 都会构造新容器并逐个赋值;若嵌套数组很大(比如上万元素),频繁调用会明显拖慢速度。
可改用迭代器方式原地读取,减少中间对象:
std::vector<int> scores;
scores.reserve(item["scores"].size()); // 预分配避免多次 realloc
for (const auto& s : item["scores"]) {
scores.push_back(s.get<int>());
}
注意:reserve() 有效前提是能预估大小;若数组长度波动大,省略它比错误预估更稳妥。另外,nlohmann::json 默认深拷贝,传参时用 const nlohmann::json& 避免意外复制整个树。
最易被忽略的是字段名拼写和大小写——JSON 是大小写敏感的,"Tags" 和 "tags" 是两个键,运行时不报错但取不到值,结果 vector 为空,这种 bug 很难一眼发现。








