JsonArray::remove()
Description
JsonArray::remove()
removes the element at the specified index from the array pointed by the JsonArray
.
If the JsonArray
is null/unbound, this function does nothing.
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);
serializeJsonPretty(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"
}
]
}
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);
}
}
serializeJsonPretty(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"
}
]
}