JsonObject::operator[]
Description
JsonObject::operator[]
gets, replaces, or adds a value in the object pointed by the JsonObject
.
JsonObject::operator[]
is a shortcut for JsonObject::getMember()
, JsonObject::getOrAddMember()
, and JsonVariant::set()
.
If the JsonObject
is null, this function does nothing.
If you need to know if the insertion succeed, use JsonVariant::set()
instead.
Signatures
MemberProxy operator[](char* key) const;
MemberProxy operator[](const char* key) const;
MemberProxy operator[](const __FlashStringHelper* key) const;
MemberProxy operator[](const String& key) const;
MemberProxy operator[](const std::string& key) const;
Arguments
key
: the key that the value will be associated with.
As usual, ArduinoJson makes a copy of the key in the JsonDocument
, except if it’s a const char*
.
Return value
JsonObject::operator[]
return a proxy class that allows using the JsonObject
like a dictionary.
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 MemberProxy
calls JsonObject::getMember()
. In other words, the two following lines are equivalent:
JsonVariant value = object["key"];
JsonVariant value = object.getMember("key");
When used for writing, the MemberProxy
calls JsonObject::getOrAddMember()
and JsonVariant::set()
. In other words, the two following lines are equivalent:
object["key"] = "value";
object.getOrAddMember("key").set("value");
MemberProxy
also exposes the same methods as JsonVariant
. For example, all the following lines are correct:
object["key"].as<int>();
object["key"].is<int>();
object["key"]["nested key"] = "nested value";
object["key"].createNestedObject();
object["key"].createNestedArray("nested");
// etc.
Remarks
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
StaticJsonDocument<256> doc;
JsonObject object = doc.to<JsonObject>();
object["hello"] = "world";
const char* world = object["hello"];