实例化json_pointer无法更新nlohmann::json文档该如何解决?
问题原因
你显式指定nlohmann::json_pointer的模板参数为std::string时,生成的类型与nlohmann::json默认接受的json_pointer类型不匹配,导致operator[]没有命中json_pointer的重载版本,反而触发了接受普通字符串键的重载,直接把整段路径当成了单个key插入。
修复方案
- 方法1:使用
nlohmann::json内置的json_pointer别名构造,不需要手动指定模板参数,是最常用的稳妥写法
nlohmann::json root; std::string path = "/foo/bar"; root[nlohmann::json::json_pointer(path)] = 42; std::cout << root.dump(4) << std::endl;
- 方法2:调用json_pointer的静态parse方法构造
root[nlohmann::json_pointer<nlohmann::json::string_t>::parse(path)] = 42;
两种方法都可以得到预期的嵌套结构输出。
内容的提问来源于stack exchange,提问作者eramos
相关产品推荐
相关产品推荐

