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 because; 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

char json[] = "{\"first\":\"hello\",\"second\":\"world\"}";
DynamicJsonDocument doc(1024);
deserializeJson(doc, json);
JsonObject root = doc.as<JsonObject>();

// using C++11 syntax (preferred):
for (JsonPair kv : root) {
    Serial.println(kv.key().c_str());
    Serial.println(kv.value().as<char*>());
}

// using C++98 syntax (for older compilers):
for (JsonObject::iterator it=root.begin(); it!=root.end(); ++it) {
    Serial.println(it->key().c_str());
    Serial.println(it->value().as<char*>());
}

The code above would print:

first
hello
second
world

See also