Add JsonMerge().

Closes #15.
This commit is contained in:
Jordan Bancino 2023-11-06 19:59:46 -05:00
parent 01da37f7d7
commit ba1ac5b42b
2 changed files with 38 additions and 0 deletions

View file

@ -1433,3 +1433,32 @@ finish:
va_end(argp); va_end(argp);
return val; 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));
}
}
}

View file

@ -320,4 +320,13 @@ extern JsonValue * JsonGet(HashMap *, size_t,...);
*/ */
extern JsonValue * JsonSet(HashMap *, JsonValue *, 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 */ #endif /* CYTOPLASM_JSON_H */