Description

When the JsonDocument contains an array, JsonDocument::add() appends a value to the array.

When the JsonDocument contains a value that is not an array, JsonDocument::add() does nothing.

When the JsonDocument is empty, JsonDocument::add() converts the JsonDocument to an array containing one element.

This feature allows creating an array without calling JsonDocument::to<JsonArray(). For example the two following snippets are equivalent:

JsonArray arr = doc.to<JsonArray>();
arr.add(42);
doc.clear();
doc.add(42);

Signatures

// add the specified value to the array
bool add(bool value);

bool add(float value);
bool add(double value);

bool add(signed char value);
bool add(signed long value);
bool add(signed int value);
bool add(signed short value);
bool add(unsigned char value);
bool add(unsigned long value);
bool add(unsigned int value);
bool add(unsigned short value);

bool add(char *value); // see Remarks
bool add(const char *value);
bool add(const __FlashStringHelper *value); // see Remarks

bool add(const String &value); // see Remarks
bool add(const std::string &value); // see Remarks

bool add(JsonArray array);
bool add(JsonObject object);
bool add(JsonVariant variant);

Arguments

value: the value of to append to the array, it can be any type supported by ArduinoJson.

If you pass a JsonArray, a JsonObject, or a JsonVariant, JsonDocument::add() makes a complete clone of the argument. In other words, the value is stored by copy, not by reference.

As usual, ArduinoJson makes a copy of a string in the JsonDocument, except if it’s a const char*.

Return value

JsonDocument::add() returns a bool that tells whether the operation was successful or not:

  • true if the value was successfully added.
  • false if there was not enough memory in the JsonDocument.

Remarks

ArduinoJson makes a copy of the string when you call this function with one of the following types:

This duplication consumes some space in the JsonDocument; don’t forget to increase its capacity accordingly.

Example

StaticJsonDocument<200> doc;
array.add("hello"); // null -> ["hello"]
array.add(3.14156); // ["hello"] -> ["hello",3.14156]
serializeJson(doc, Serial);

will write

["hello",3.14156]

See also