Would love a deep-merge function in the ArduinoJson library
Created by: nsbawden
Deep merging two JSON objects is very commonly done when using JSON objects as state management and cross platform communication packages. For instance, using the ArduinoJson library to pass a JSON object back and forth between an ESP webserver and a hardware controlling Arduino processor allows very simple and flexible variable and state updates on both sides without needing to change the ESP server code for every new variable added on the Arduino side. Passing partial JSON representing only changed values makes the update transfers very efficient, but requires a deep JSON merge in order to easily synchronize updates on both ends. Similar to how JQuery extend
is so often used.
Here is my attempt at a deep merge (or extend). It appears to work in my tests. Hopefully I have covered all the possible failure (i.e. memory allocation failure) cases sufficiently. Please consider adding a deep merge like this to the ArduinoJson library. I believe it would be used a lot once people realize it's great power in JSON based state and message engines, and many other JSON uses.
Thanks! And I love ArduinoJson ... great work!
bool deepMergeJson(JsonObject dest, JsonObjectConst src) {
for (auto kvp : src) {
if (kvp.value().is<JsonObject>()) {
if (!dest.containsKey(kvp.key())) {
if (!dest.createNestedObject(kvp.key()))
return false;
}
if (!deepMergeJson(dest[kvp.key()], kvp.value()))
return false;
}
else {
if (!dest[kvp.key()].set(kvp.value()))
return false;
}
}
return true;
}
And / or, at the very least, add this (improving if needed) to the merge How To
? ... Since a full merge is exponentially more useful than a single level merge, but not so easy for many users to write correctly on their own. I wasn't sure if any internal JsonDocument memory cleanup might be needed after each full merge for regular/many merges to be done on the same document or if that is handled automatically. Thanks again. :)