Description

Gets the JsonVariant at the specified key.

Instead of this function, you can use JsonObject::operator[] which offers a more intuitive syntax.

Signatures

JsonVariant get(const char* key) const;
JsonVariant get(String key) const;
JsonVariant get(std::string key) const;
JsonVariant get(const __FlashStringHelper* key) const;

Arguments

key: the key of the value in the object.

Return value

The JsonVariant at the specified key.

If the key is not found, this function returns a null JsonVariant.

Examples

The key is not found

Here is a program that shows what happens when the key is not found.

char json[] = "{\"username\":\"the_duke\"}";

StaticJsonDocument<256> doc;
deserializeJson(doc, json);

JsonObject object = doc.as<JsonObject>();

JsonVariant password = object.get("password");
if (password.isNull()) {
  Serial.println(F("Error: password is missing"));
}

This program prints:

Error: password is missing

The key is found

Here is a program that shows what happens when the key is found.

char json[] = "{\"username\":\"the_duke\"}";

StaticJsonDocument<256> doc;
deserializeJson(doc, json);

JsonObject object = doc.as<JsonObject>();

JsonVariant username = object.get("username");
Serial.println(F("Your name is: "));
Serial.println(username.as<const char*>());

This program prints:

Your name is: the_duke

See also