Description

JsonObject::remove() removes a key-value pair from the object pointed by the JsonObject.

If the JsonObject is null, this function does nothing.

Causes memory leaks ⚠️

Because JsonDocument contains a monotonic allocator, this function cannot release the memory associated with the removed key-value pair.
Consequently, you cannot call this function in a loop; otherwise, the JsonDocument will overflow.

Signatures

void remove(const char* key) const;
void remove(const __FlashStringHelper* key) const;

void remove(const String& key) const;
void remove(const std::string& key) const;

void remove(JsonObject::iterator) const;

Arguments

key: the key to remove from the object.

Example

In the following examples, we will use this JSON document as input:

{
  "Survivors": {
    "Coach": {
      "age": 40,
      "sex": "male",
      "occupation": "teacher"
    },
    "Ellis": {
      "age": 23,
      "sex": "male",
      "occupation": "mechanic"
    },
    "Nick": {
      "age": 35,
      "sex": "male",
      "occupation": "retailer"
    },
    "Rochelle": {
      "age": 29,
      "sex": "female",
      "occupation": "associate producer"
    }
  }
}

Remove a member with the specified key

Here is how you can remove “Ellis” from the crew:

deserializeJson(doc, input);
JsonObject crew = doc["Survivors"];
crew.remove("Ellis");
serializeJsonPrety(object, Serial);

Execute this program and it will print the following to the serial:

{
  "Survivors": {
    "Coach": {
      "age": 40,
      "sex": "male",
      "occupation": "teacher"
    },
    "Nick": {
      "age": 35,
      "sex": "male",
      "occupation": "retailer"
    },
    "Rochelle": {
      "age": 29,
      "sex": "female",
      "occupation": "associate producer"
    }
  }
}

Again, this doesn’t release the associate memory, which can create a memory leak.

Remove all members matching a criteria

Here is how you can remove all female characters from the crew:

deserializeJson(doc, input);
JsonObject crew = doc["Survivors"];

for (JsonObject::iterator it=crew.begin(); it!=crew.end(); ++it) {
  if (it->value()["sex"] == "female") {
     crew.remove(it);
  }
}

serializeJsonPrety(object, Serial);

Run this program and it will write theses lines to the serial:

{
  "Survivors": {
    "Coach": {
      "age": 40,
      "sex": "male",
      "occupation": "teacher"
    },
    "Ellis": {
      "age": 23,
      "sex": "male",
      "occupation": "mechanic"
    },
    "Nick": {
      "age": 35,
      "sex": "male",
      "occupation": "retailer"
    }
  }
}

We said it several times, but it’s worth repeating: remove() doesn’t release the associate memory, which can create a memory leak.

See also