How to recursively search for a key?
The function below recursively searches for a key in a JsonObject
. It allows you to find a key in nested objects.
JsonVariant findNestedKey(JsonObject obj, const char* key) {
JsonVariant foundObject = obj[key];
if (!foundObject.isNull())
return foundObject;
for (JsonPair pair : obj) {
JsonVariant nestedObject = findNestedKey(pair.value(), key);
if (!nestedObject.isNull())
return nestedObject;
}
return JsonVariant();
}
For example, suppose you have this JSON document:
{
"europe": {
"france": {
"paris": 2165423,
"marseille": 870731,
},
"italy": {
"rome": 2844395,
"milan": 3368590,
},
}
}
You could use this function below to find the population of Paris, like so:
unsigned long parisPopulation = findNestedKey(doc.as<JsonObject>(), "paris");
In addition, if you want to support constant references, you need to use this overload:
JsonVariantConst findNestedKey(JsonObjectConst obj, const char* key) {
JsonVariantConst foundObject = obj[key];
if (!foundObject.isNull())
return foundObject;
for (JsonPairConst pair : obj) {
JsonVariantConst nestedObject = findNestedKey(pair.value(), key);
if (!nestedObject.isNull())
return nestedObject;
}
return JsonVariantConst();
}