JsonArray::operator[]
Description
JsonArray::operator[]
gets or replaces a value in the array pointed by the JsonArray
.
JsonArray::operator[]
is a shortcut for JsonArray::getElement()
and JsonVariant::set()
.
If the JsonArray
is null, this operator does nothing.
If you need to know if the insertion succeed, use JsonVariant::set()
instead.
Don’t use this operator to get all values; instead, use iterators.
Signatures
ElementProxy operator[](size_t index) const;
Argument
index
: the zero-based position of the value in the array.
Return value
JsonArray::operator[]
returns a proxy class that allows you to use the JsonArray
as a C array.
If this concept of proxy class is unfamiliar to you, just think of a JsonVariant
instead.
How does it work?
When used for reading, the ElementProxy
calls JsonArray::getElement()
. In other words, the two following lines are equivalent:
JsonVariant value = array[0];
JsonVariant value = array.getElement(0);
When used for writing, the ElementProxy
calls JsonArray::getElement()
and JsonVariant::set()
. In other words, the two following lines are equivalent:
array[0] = "value";
array.getElement(0).set("value");
ElementProxy
also exposes the same methods as JsonVariant
. For example, all the following lines are correct:
array[0].as<int>();
array[0].is<int>();
array[0]["nested key"] = "nested value";
array[0].createNestedObject();
array[0].createNestedArray();
// etc.
Example
JsonArray array = doc.to<JsonArray>();
array.add(42);
int value = array[0];
array[0] = 666;