【问题标题】:How to erase item inside of item in nlohmann::json file C++如何在 nlohmann::json 文件 C++ 中擦除项目内的项目
【发布时间】:2021-06-24 18:56:55
【问题描述】:

我想知道如何删除 nlohmann::json C++ 库中项目中的项目。

Json 示例文件:

{
    "Users":{
        "User1":{
            "Name":"BOB",
            "DeleteMe":"IWantToBeDeleted!"
        }
    }
}

我要删除的是 "DeleteMe":"IWantToBeDeleted!"即在“用户”和“用户 1”内 我查看了basic_json::erase 的文档,但我只能看到如何删除 json 文件根目录中的项目,例如我的示例文件中的“用户”。

任何帮助将不胜感激 =D

【问题讨论】:

  • 我认为你可以通过json_pointererase 的组合来做你需要的事情。使用指针获取对User1 节点的引用,并使用erase 删除DeleteMe 节点

标签: c++ json nlohmann-json


【解决方案1】:

basic_json::erase 只会从当前引用的json 节点中擦除——所以如果你的json 对象是外部对象,这就是你只能擦除顶级条目的原因。您想要的是一种获取内部节点User1 并从那里调用DeleteMe 键上的erase 的方法。

您应该能够使用json_pointer 轻松获得对User1 的引用——这基本上是遍历以获得所需节点所需的节点的字符串路径。一旦你有了节点,它应该就像调用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

【讨论】:

  • 这可以通过使用 json_pointer 本身提供的两个简洁的函数来稍微改进,parent_pointer()back(),所以没有必要拆分 key path "手动" auto ptr = nlohmann::json::json_pointer( "/Users/User1/DeleteMe" ); json.at( ptr.parent_pointer() ).erase( ptr.back() ); gcc.godbolt.org/z/avxT5q9YP
猜你喜欢
  • 1970-01-01
  • 2016-12-11
  • 1970-01-01
  • 2020-09-05
  • 2023-02-23
  • 2022-01-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多