How to erase item inside of item in nlohmann::json file C++

Viewed 1311

I want to know how I can delete an item within an item in the nlohmann::json C++ library.

Json example file:

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

What I want to delete is "DeleteMe":"IWantToBeDeleted!" that is inside of "Users" and "User1" I have looked at the documentation for basic_json::erase but I can only see how to delete an item in the root of the json file, for example "Users" in my example file.

Any help would be appreciated =D

1 Answers

basic_json::erase only erases from the currently referenced json node -- so if your json object is the outer object, that would be why you can only erase top-level entries. What you want is a way to get the internal node User1 and call erase on the DeleteMe key from there.

You should be able to easily get a reference to User1 using json_pointer -- which is basically a string-path of the nodes required to traverse to get the node you want. Once you have the node, it should be as simple as calling erase.

Something like this:

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

Related