JsonVariant::containsKey()
Description
JsonVariant::containsKey()
tests whether a key exists in the object pointed by the JsonVariant
.
This function only works if the JsonVariant
points to an object. It returns false
if the JsonVariant
is null, or if it points to an array.
Signature
bool containsKey(const char* key) const;
bool containsKey(const String& key) const;
bool containsKey(const std::string& key) const;
bool containsKey(const __FlashStringHelper& key) const;
bool containsKey(std::string_view key) const;
Arguments
key
: the key to look for.
Return value
JsonVariant::containsKey()
returns a bool
that tells whether the key was found or not:
true
if the key is present in the objectfalse
if the key is absent of the object
Example
JsonDocument doc;
JsonVariant root = doc.to<JsonVariant>();
root["city"] = "Paris";
bool hasCity = root.containsKey("city"); // true
bool hasCountry = root.containsKey("country"); // false
Avoid this function when you can!
The function can be avoided most of the time.
Because ArduinoJson implements the Null Object Pattern, it is always safe to read the object: if the key doesn’t exist, it returns an empty value.
For example:
if (root.containsKey("error")) { const char* error = root["error"] Serial.println(error); return; }
Can be written like this:
JsonVariant error = root["error"]; if (!error.isNull()) { Serial.println(error.as<const char*>()); return; }
This can even be simplified further if the default value (
0
orNULL
) is not within the acceptable range:const char* error = root["error"]; if (error) { Serial.println(error); return; }
This version should lead to a smaller and faster code since it only does the lookup once.
How to test nested keys?
You cannot test the presence of nested keys with
containsKey()
but, as explained above, it’s safe to read the object anyway.For example, when Weather Underground returns an error like:
{ "response": { "version": "0.1", "termsofService": "http://www.wunderground.com/weather/api/d/terms.html", "features": { "conditions": 1 }, "error": { "type": "querynotfound", "description": "No cities match your search query" } } }
You should not try to call
containsKey("response")
,containsKey("error")
andcontainsKey("description")
. Instead, just get the value and test if it’sNULL
:const char* error = root["response"]["error"]["description"]; if (error) { Serial.println(error); return; }