我想知道如何删除 nlohmann::json 中的项目中的项目C++ 库。
JSON 示例文件:
{
"Users":{
"User1":{
"Name":"BOB",
"DeleteMe":"IWantToBeDeleted!"
}
}
}
我要删除的是 "DeleteMe":"IWantToBeDeleted!"位于“用户”和“用户 1”内我查看了 basic_json::erase 的文档但我只能看到如何删除 json 文件根目录中的项目,例如我的示例文件中的“用户”。
任何帮助将不胜感激 =D
最佳答案
basic_json::erase
仅从当前引用的 json
中删除节点——所以如果你的 json
object 是外部对象,这就是您只能删除顶级条目的原因。你想要的是一种获取内部节点的方法User1
并调用 erase
在 DeleteMe
key 从那里。
您应该能够轻松获得对 User1
的引用。使用 json_pointer
-- 这基本上是遍历以获取所需节点所需的节点的字符串路径。一旦你有了节点,它应该就像调用 erase
一样简单。 .
像这样的东西:
auto json = nlohmann::json{/* some json object */};
auto path = nlohmann::json_pointer<nlohmann::json>{"/Users/User1"};
// Get a reference to the 'user1' json object at the specified path
auto& user1 = json[path];
// Erase from the 'user1' node by key name
user1.erase("DeleteMe");
Live Example
关于c++ - 如何在 nlohmann::json 文件 C++ 中删除项目内的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68121375/