Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merging two JSON objects #4

Open
bpawlik opened this issue Dec 6, 2021 · 2 comments
Open

Merging two JSON objects #4

bpawlik opened this issue Dec 6, 2021 · 2 comments

Comments

@bpawlik
Copy link

bpawlik commented Dec 6, 2021

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

@garrisonhh
Copy link
Owner

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.

@bpawlik
Copy link
Author

bpawlik commented Dec 17, 2021

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants