Description

JsonArray::remove() removes the element at the specified index from the array pointed by the JsonArray.

If the JsonArray 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.

Signature

void remove(size_t index) const;

void remove(JsonArray::iterator iterator) const;

Arguments

index: the zero-based position of the element in the array.

iterator: an iterator returned by JsonArray::begin().

Examples

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

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

Example 1: Remove the element at specified index

If you want to remove the second member of the crew, you can simply use its index (1, since the indexing starts at zero):

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

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

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

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

Example 2: Remove all elements matching a criteria

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

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

for (JsonArray::iterator it=crew.begin(); it!=crew.end(); ++it) {
  if ((*it)["sex"] == "female") {
     crew.remove(it);
  }
}

serializeJsonPrety(object, Serial);

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

{
  "Survivors": [
    {
      "name": "Coach",
      "age": 40,
      "sex": "male",
      "occupation": "teacher"
    },
    {
      "name": "Ellis",
      "age": 23,
      "sex": "male",
      "occupation": "mechanic"
    },
    {
      "name": "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

 X online