4

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

Piboy314
  • 186
  • 1
  • 15
  • I think you can probably do what you need with a combination of [`json_pointer`](http://nlohmann.github.io/json/doxygen/classnlohmann_1_1json__pointer_a7f32d7c62841f0c4a6784cf741a6e4f8.html) and `erase`. Use the pointer to get *a reference* to the `User1` node, and `erase` to remove the `DeleteMe` node – Human-Compiler Jun 24 '21 at 19:16

1 Answers1

5

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

Human-Compiler
  • 11,022
  • 1
  • 32
  • 59
  • This can be slightly improved by using two neat functions provided by _json_pointer_ itself, `parent_pointer()` and `back()`, so there's no need to split key path "_manually_" `auto ptr = nlohmann::json::json_pointer( "/Users/User1/DeleteMe" ); json.at( ptr.parent_pointer() ).erase( ptr.back() );` https://gcc.godbolt.org/z/avxT5q9YP – Samira Oct 10 '21 at 20:10