JsonDocument::operator[]
Description
JsonDocument::operator[]
gets, replaces, or adds a value in the JsonDocument
.
Depending on the argument type the JsonDocument
can be used like a JsonArray
or a JsonObject
.
If you use this operator to set a value in an empty JsonDocument
, it automatically converts JsonDocument
to the appropriate type. This feature allows creating object without calling JsonDocument::to<JsonObject>()
. Here is an example:
StaticJsonDocument<256> doc;
doc["wifi"]["SSID"] = "TheBatCave";
The two lines above create the following document:
{
"wifi": {
"SSID": "TheBatCave"
}
}
All types are stored by copy, except const char*
which is stored by pointer.
If you need to know if the insertion succeed, use JsonVariant::set()
instead.
Signatures
// mimics a JsonArray
ElementProxy operator[](size_t index);
// mimics a JsonObject
MemberProxy operator[](const char* key); // ⚠️ stores key as a pointer
MemberProxy operator[](char* key);
MemberProxy operator[](const String& key);
MemberProxy operator[](const std::string& key);
MemberProxy operator[](const __FlashStringHelper* key);
MemberProxy operator[](std::string_view key);
You can also call JsonDocument::operator[]
on a constant JsonDocument
, but the return type will be a JsonVariantConst
, a read-only version of JsonVariant
.
Arguments
index
: the index in the JsonArray
.
key
: the key in the JsonObject
Return value
A proxy class that allows using the JsonDocument
as an array or a dictionary. If this concept of proxy class is unfamiliar to you, just think of a JsonVariant
instead.
Please see JsonArray::operator[]
and JsonObject::operator[]
for explanations about ElementProxy
and MemberProxy
.
Example
DynamicJsonDocument doc(1024);
deserializeJson(doc, "{\"hello\":\"world\"}");
const char* hello = variant["hello"];
deserializeJson(doc, "[\"hello\",\"world\"]");
const char* world = variant[1];