Description

JsonArray::add() appends a value to the array pointed by the JsonArray.

If the JsonArray is null, this function does nothing.

Signatures

bool add(bool value) const;

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

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

bool add(char *value) const;                       // stores by copy
bool add(const char *value) const;                 // stores by pointer
bool add(const __FlashStringHelper *value) const;  // stores by copy

bool add(const String &value) const;       // stores by copy
bool add(const std::string &value) const;  // stores by copy
bool add(const Printable& value)           // 🆕 (added in 6.18.0)
bool add(std::string_view value)           // 🆕 (added in 6.18.1)

bool add(JsonArray array) const;          // stores by copy
bool add(JsonObject object) const;        // stores by copy
bool add(JsonVariant variant) const;      // stores by copy
bool add(const JsonDocument& doc) const;  // stores by copy

bool add(TEnum value) const;  // alias of add(int)
bool add(T value) const;      // 🆕 calls user-defined function (added in 6.18.0)

Arguments

value: the value to add to the array.

If you pass a JsonArray, a JsonObject, or a JsonVariant, JsonArray::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

JsonArray::add() return 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.

String duplication

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.

User-defined types 🆕

JsonArray::add() supports user-defined types by calling convertToJson(). For example, to support tm, you must define:

bool convertToJson(const tm& src, JsonVariant dst) {
  char buf[32];
  strftime(buf, sizeof(buf), "%FT%TZ", &src);
  return dst.set(buf);
}

This feature was added in ArduinoJson 6.18.0, see article for details.

Example

StaticJsonDocument<200> doc;
JsonArray array = doc.to<JsonArray>();
array.add("hello");
array.add(3.14156);
serializeJson(doc, Serial);

will write

["hello",3.14156]

See also