Description

Depending on the argument, JsonDocument::createNestedObject() behaves like JsonArray::createNestedObject() or JsonObject::createNestedObject().

Without argument, JsonDocument::createNestedObject() creates an object and appends it to the root array. If the document’s root is not an array, this function does nothing. If the document is empty, this function initializes the document’s root as an array.

With a string argument, JsonDocument::createNestedObject() creates an object and assigns it to the specified key. If the document’s root is not an object, this function does nothing. If the document is empty, this function initializes the document’s root as an object.

As you see, when the JsonDocument is empty, this function automatically converts it to the appropriate type (array or object). This feature allows creating nested objects like that:

DynamicJsonDocument doc(1024);
JsonArray wifi  = doc.createNestedObject("wifi");
wifi["SSID"] = "TheBatCave";

The lines above create the following document:

{
    "wifi": {
        "SSID": "TheBatCave"
    }
}

Signature

// similar to JsonArray::createNestedObject()
JsonObject createNestedObject();

// similar to JsonObject::createNestedObject()
JsonObject createNestedObject(char* key);
JsonObject createNestedObject(const char* key);
JsonObject createNestedObject(const __FlashStringHelper* key);
JsonObject createNestedObject(const String& key);
JsonObject createNestedObject(const std::string& key);

Return value

JsonDocument::createNestedObject() returns a JsonObject that points to the new array.

JsonDocument::createNestedObject() returns null when the memory allocation fails; in which case JsonObject::isNull() return true.

Examples

Like an array

StaticJsonDocument<200> doc;

JsonObject obj = doc.createNestedObject();
obj["hello"] = "world";

serializeJson(doc, Serial);

will write

[{"hello":"world"}]

Like an object

StaticJsonDocument<200> doc;

JsonObject obj = doc.createNestedObject("nested");
obj["hello"] = "world";

serializeJson(doc, Serial);

will write

{"nested":{"hello":"world"}}

See also