Description

Changes the value returned when the JsonVariant is undefined or incompatible.

In other words, it changes the default value.

This feature was introduced in version 5.12.

Signatures

bool               operator|(bool defaultValue) const;

float              operator|(float defaultValue) const;
double             operator|(double defaultValue) const;

signed char        operator|(signed char defaultValue) const;
unsigned char      operator|(unsigned char defaultValue) const;
signed int         operator|(signed int defaultValue) const;
unsigned int       operator|(unsigned int defaultValue) const;
signed short       operator|(signed short defaultValue) const;
unsigned short     operator|(unsigned short defaultValue) const;
signed long        operator|(signed long defaultValue) const;
unsigned long      operator|(unsigned long defaultValue) const;
unsigned long long operator|(unsigned long long defaultValue) const; // <- may require ARDUINOJSON_USE_LONG_LONG
signed long long   operator|(signed long long defaultValue) const;   // <- may require ARDUINOJSON_USE_LONG_LONG

const char*        operator|(char* defaultValue) const;
const char*        operator|(const char* defaultValue) const;
String             operator|(String defaultValue) const;
std::string        operator|(const std::string& defaultValue) const;

Arguments

defaultValue: the value to return is the JsonVariant is undefined or incompatible.

Return value

  • The value of the variant, if it can be converted to the type of defaultValue.
  • defaultValue if not.

Remark: even if JsonVariant::is<char*>() returns true for null, the operator | returns defaultValue when that happens.

Example

int port = config["port"] | 80;
strlcpy(hostname, config["hostname"] | "example.com", sizeof(hostname));

Pitfall ⚠️

When you use this operator, the type of the expression is inferred from the type of the default value.

Here is an example where this fact matters:

long value = root["key"] | -1;

In this example, the right side of the expression returns an int (and not a long as one could expect) because the default value is an integer. If root["key"] contains a big value, the integer overflows and you get a seemingly random result in value.

To fix this, you need to change the type of the default value:

long value = root["key"] | -1L;

See also