JsonVariantConst::operator|() provides default value for a JsonVariantConst.


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;


defaultValue: the value to return if the JsonVariantConst is null or incompatible with the requested type.

Unlike JsonVariantConst::as<T>() that uses a template parameter to specify the requested type, JsonVariantConst::operator|() infers the requested type from the argument defaultValue. Usually, that’s what you want but can lead to odd results as described below.

Return value

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


int port = config["port"] | 80;
strlcpy(hostname, config["hostname"] | "", 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;

Lastly, you cannot combine this operator with JsonVariantConst::as<T>(). For example, you cannot write:

// this line compiles but it doesn't do what you think
long value = root["key"].as<long>() | 1; // WRONG!!!!

See also