diff --git a/src/Json.c b/src/Json.c index 6922e14..10a0316 100644 --- a/src/Json.c +++ b/src/Json.c @@ -1433,3 +1433,32 @@ finish: va_end(argp); return val; } + +void +JsonMerge(HashMap *obj1, HashMap *obj2) +{ + char *key; + JsonValue *val2; + + while (HashMapIterate(obj2, &key, (void **) &val2)) + { + JsonValue *val1 = HashMapGet(obj1, key); + + if (val1) + { + if (JsonValueType(val1) == JsonValueType(val2) && + JsonValueType(val1) == JSON_OBJECT) + { + JsonMerge(JsonValueAsObject(val1), JsonValueAsObject(val2)); + } + else + { + JsonValueFree(HashMapSet(obj1, key, JsonValueDuplicate(val2))); + } + } + else + { + HashMapSet(obj1, key, JsonValueDuplicate(val2)); + } + } +} diff --git a/src/include/Json.h b/src/include/Json.h index cc4a63d..5a14aab 100644 --- a/src/include/Json.h +++ b/src/include/Json.h @@ -320,4 +320,13 @@ extern JsonValue * JsonGet(HashMap *, size_t,...); */ extern JsonValue * JsonSet(HashMap *, JsonValue *, size_t,...); +/** + * Recursively merge two JSON objects. The second object is merged + * on top of the first; any keys present in the first object that are + * also present in the second object are replaced with those in the + * second object, and any keys present in the second object that are + * not present in the first object are copied to the first object. + */ +extern void JsonMerge(HashMap *, HashMap *); + #endif /* CYTOPLASM_JSON_H */