如何基于键名向量构建嵌套nlohmann JSON并修改最深层级
高效构建嵌套nlohmann JSON并访问最深层级
问题背景
给定一个键名字符串向量,需要构建嵌套的nlohmann JSON结构,例如对于{"a", "b", "c"},生成如下结构:
{ "a" : { "b" : { "c" : { } } } }
后续需要频繁修改最深层级的内容(如调用merge_patch),但键向量长度可变,无法硬编码层级访问逻辑。原反向遍历构建的方式会产生大量临时JSON对象,效率低且无法直接获取最深层级的访问入口。
解决方案
方案1:构建时同时返回根对象和最深层级指针
通过正向遍历键向量,逐步创建嵌套节点,同时跟踪最深层级的指针,既避免临时对象开销,又直接拿到目标层级的访问入口:
#include <nlohmann/json.hpp> #include <vector> #include <utility> using json = nlohmann::json; std::pair<json, json*> createNestedJson(const std::vector<std::string>& keys) { json root = json::object(); json* current = &root; for (const auto& key : keys) { // 为当前键创建空对象节点 current->emplace(key, json::object()); // 移动指针到下一层级 current = &((*current)[key]); } return {std::move(root), current}; }
使用示例:
std::vector<std::string> keys = {"a", "b", "c"}; auto [myJson, deepestNode] = createNestedJson(keys); // 直接对最深层级执行merge_patch deepestNode->merge_patch(newJson1); deepestNode->merge_patch(newJson2);
方案2:动态定位/创建最深层级(适用于已有根对象的场景)
如果已经存在根JSON对象,可通过辅助函数动态定位或创建目标层级,无需提前完整构建嵌套结构:
#include <nlohmann/json.hpp> #include <vector> using json = nlohmann::json; json& getDeepestNode(json& root, const std::vector<std::string>& keys) { json* current = &root; for (const auto& key : keys) { // 若键不存在或对应节点非对象,则创建空对象 if (!current->contains(key) || !(*current)[key].is_object()) { (*current)[key] = json::object(); } current = &((*current)[key]); } return *current; }
使用示例:
json myJson = json::object(); std::vector<std::string> keys = {"a", "b", "c"}; // 获取最深层级的引用 json& deepestNode = getDeepestNode(myJson, keys); deepestNode.merge_patch(newJson1); deepestNode.merge_patch(newJson2);
方案优势
- 避免原反向遍历中的临时对象拷贝,内存和时间效率更高
- 直接获取最深层级的引用/指针,后续修改操作无需重复遍历键向量
- 方案2支持动态创建节点,兼容已有部分结构的JSON对象
内容的提问来源于stack exchange,提问作者ZZZ
相关产品推荐
相关产品推荐

