diff --git a/Bag-of-Tricks.md b/Bag-of-Tricks.md index 5fc8b09..8f4c33d 100644 --- a/Bag-of-Tricks.md +++ b/Bag-of-Tricks.md @@ -109,6 +109,65 @@ root["value2"] = RawJson("[[\"Yes\",\"No\"],[\"Maybe\"]"); See issue [#252](https://github.com/bblanchon/ArduinoJson/issues/252) +## Merging JSON objects + +Suppose we have three JSON objects like these: + +```c++ +char json1[] = R"({ + "fingerprint": "1234" + })"; + +char json2[] = R"({ + "Trait1":{ + "someValue": "4321" + } + })"; + +char json3[] = R"({ + "Trait2":{ + "anotherValue": "5555" + } + })"; + +JsonObject& jsonObjectRoot = jsonBuffer1.parseObject(json1); +JsonObject& jsonObjectOne = jsonBuffer2.parseObject(json2); +JsonObject& jsonObjectTwo = jsonBuffer3.parseObject(json3); +``` +And we want a JSON that looks like this: + +```json +{ + "fingerprint": "1234", + "SetOfObjects" : { + "Trait1":{ + "someValue": "4321" + }, + "Trait2":{ + "anotherValue": "5555" + } + } +} +``` + +This function allows to merge the JSON objects: + +```c++ +void merge(JsonObject& dest, JsonObject& src) { + for (auto kvp : src) { + dest[kvp.key] = kvp.value; + } +} +``` +Usage: +```c++ +JsonObject& nestedObject = jsonObjectRoot.createNestedObject("SetOfObjects"); +merge(nestedObject, jsonObjectOne); +merge(nestedObject, jsonObjectTwo); +``` + +See issue [#332](https://github.com/bblanchon/ArduinoJson/issues/332) + ## Buffered output: Here is a proxy that will put bytes in a buffer before actually writing them to the destination: