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:

JsonDocument 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

// Shared with JsonArray
ElementProxy operator[](size_t index);

// Shared with JsonArrayConst
JsonVariantConst operator[](size_t index) const;

// Shared with JsonObject
MemberProxy operator[](char* key);
MemberProxy operator[](const char* key);  // ⚠️ stores key as a pointer
MemberProxy operator[](const String& key);
MemberProxy operator[](const std::string& key);
MemberProxy operator[](const __FlashStringHelper* key);
MemberProxy operator[](std::string_view key);

// Shared with JsonObjectConst
JsonVariantConst operator[](const char* key) const;
JsonVariantConst operator[](const String& key) const;
JsonVariantConst operator[](const std::string& key) const;
JsonVariantConst operator[](const __FlashStringHelper* key) const;
JsonVariantConst operator[](std::string_view key) const;

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

JsonDocument doc;

deserializeJson(doc, "{\"hello\":\"world\"}");
const char* hello = variant["hello"];

deserializeJson(doc, "[\"hello\",\"world\"]");
const char* world = variant[1];

See also