ghh_json icon indicating copy to clipboard operation
ghh_json copied to clipboard

Merging two JSON objects

Open bpawlik opened this issue 4 years ago • 2 comments

Is there an easy way to merge two JSON objects? E.g. if they have the same keys then overwrite, otherwise add new?

Thanks, Bartek

bpawlik avatar Dec 06 '21 00:12 bpawlik

Unfortunately not in the current version! I recently made a branch specifically to deal with meta stuff like this, for now I would point you to the object-reflection branch.

Here's a quick example of how I would copy data from one object to another using two new functions (get_keys and put_copy):

test.json

{
    "first": {
        "a": true,
        "b": false
    },
    "second": {}
}
#define GHH_JSON_IMPL
#include "ghh_json.h"

void main() {
    json_t json;
    json_load_file(&json, "test.json");

    printf("before: %s\n", json_serialize(json.root, false, 2, NULL));

    json_object_t *first = json_get_object(json.root, "first");
    json_object_t *second = json_get_object(json.root, "second");

    size_t num_keys;
    char **keys = json_get_keys(first, &num_keys);

    for (size_t i = 0; i < num_keys; ++i) {
        json_put_copy(&json, second, keys[i], json_get_object(first, keys[i]));
    }

    printf("after: %s\n", json_serialize(json.root, false, 2, NULL));

    json_unload(&json);
}

I'm not perfectly happy with some of the new features yet, so it may or may not look a little different when I merge this branch with master. Hope this is helpful, I will leave this issue open until this kind of functionality is merged.

garrisonhh avatar Dec 06 '21 02:12 garrisonhh

Thanks a lot! I just tried it and it works well.

BTW I still had to revert to using strtod for proper floats parsing. Using object-reflection branch was giving me funny numbers.

bpawlik avatar Dec 17 '21 01:12 bpawlik