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"
}
}
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);
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); // 🆕 (added in 6.18.1)
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
.
String duplication
ArduinoJson makes a copy of the string when you call this function with one of the following types:
char*
String
(orstd::string
)const __FlashStringHelper*
(i.e. Flash string)
This duplication consumes some space in the JsonDocument
; don’t forget to increase its capacity accordingly.
Example
DynamicJsonDocument doc(1024);
deserializeJson(doc, "{\"hello\":\"world\"}");
const char* hello = variant["hello"];
deserializeJson(doc, "[\"hello\",\"world\"]");
const char* world = variant[1];