Description

The member functions begin() and end() return STL-style iterators. You can use these iterators to enumerate all the key-value pairs in the object pointed by the JsonObject.

These functions reproduce the containers in the C++ Standard Library and allow you to use the “ranged-based for loop” feature of C++11. See the example below.

Signatures

JsonObject::iterator begin() const;
JsonObject::iterator end() const;

Return value

begin() returns an iterator to the first key-value pair of the object.

end() returns an iterator to the element after the last. This iterator must not be dereferenced; it’s a placeholder to detect the end of the object.

JsonObject::iterator points to a JsonPair, a class that bundles a key (accessible via JsonPair::key()) and a value (accessible via JsonPair::value()).

The type of the key is JsonString; you need to call JsonString::c_str() to get the char-pointer out of it. The type of the value is JsonVariant, as usual.

Here is a summary:

class JsonPair {
public:
  JsonString key() const;
  JsonVariant value() const;
};

class JsonString {
public:
  const char* c_str() const;
};

Example

List all keys and values of an object

JsonDocument doc;
deserializeJson(doc, "{\"first\":\"hello\",\"second\":\"world\"}");
JsonObject root = doc.as<JsonObject>();

for (JsonPair kv : root) {
    Serial.println(kv.key().c_str());
    Serial.println(kv.value().as<const char*>());
}

The code above prints:

first
hello
second
world

Get object member by index

JsonDocument doc;
deserializeJson(doc, "{\"a\":\"alpha\",\"b\":\"beta\",\"c\":\"charlie\"}");

JsonObject::iterator it = doc.as<JsonObject>().begin();

int index = 2;
for (int i = 0; i < index; i++) 
    ++it;

Serial.println(it->value().as<const char*>());  // prints "charlie"

See also

Global warming stripes by Professor Ed Hawkins (University of Reading)