JsonDocument::createNestedArray()
Description
Depending on the argument, JsonDocument::createNestedArray()
behaves like JsonArray::createNestedArray()
or JsonObject::createNestedArray()
.
Without argument, JsonDocument::createNestedArray()
creates an array 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::createNestedArray()
creates an array 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 arrays like that:
DynamicJsonDocument doc(1024);
JsonArray ports = doc.createNestedArray("ports");
ports.add("80");
ports.add("443");
The lines above create the following document:
{
"ports": [
80,
443
]
}
Signature
// similar to JsonArray::createNestedArray()
JsonArray createNestedArray();
// similar to JsonObject::createNestedArray()
JsonArray createNestedArray(char* key);
JsonArray createNestedArray(const char* key);
JsonArray createNestedArray(const __FlashStringHelper* key);
JsonArray createNestedArray(const String& key);
JsonArray createNestedArray(const std::string& key);
JsonArray createNestedArray(std::string_view key);
Return value
JsonDocument::createNestedArray()
returns a JsonArray
that points to the new array.
JsonDocument::createNestedArray()
returns null when the memory allocation fails; in which case JsonArray::isNull()
return true
.
Examples
Like an array
StaticJsonDocument<200> doc;
JsonArray arr = doc.createNestedArray();
arr.add("hello world");
serializeJson(doc, Serial);
will write the following line to the serial port:
[["hello world"]]
Like an object
StaticJsonDocument<200> doc;
JsonArray array = doc.createNestedArray("hello");
array.add("world");
serializeJson(doc, Serial);
will write the following line to the serial port:
{"hello":["world"]}