A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://arduinojson.org/v6/api/jsondocument/containskey/ below:

JsonDocument::containsKey() | ArduinoJson 6

Description

JsonDocument::containsKey() tests whether a key exists at the root of the document.

This function only works if the JsonDocument contains an object. It returns false if the JsonDocument is empty, or if it contains an array.

This function can (and should) be avoided most of the time. See below.

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

JsonDocument::containsKey() returns a bool that tells whether the key was found or not:

Example
StaticJsonDocument<256> doc;
doc["city"] = "Paris";

bool hasCity = doc.containsKey("city"); // true
bool hasCountry = doc.containsKey("country"); // false
Avoid this function when you can!

This function can (and should) 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:

StaticJsonDocument<256> doc;
doc["city"] = "Paris";

if (doc.containsKey("city")) {
  const char* city = doc["city"];
  Serial.println(city);
}

Can be written like this:

StaticJsonDocument<256> doc;
doc["city"] = "Paris";

const char* city = doc["city"];
if (city)
  Serial.println(city);

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") and containsKey("description"). Instead, just get the value and test if it’s null:

const char* error = doc["response"]["error"]["description"];
if (error) {
  Serial.println(error);
  return;
}
See also
  1. Home
  2. Version 6
  3. API
  4. JsonDocument
  5. containsKey()

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4