How to combine\merge 2 objects?

129 views
Skip to first unread message

Carlos Manuel

unread,
Nov 17, 2012, 11:05:24 PM11/17/12
to jso...@googlegroups.com

how can i combine 2 objects like $.extend(true, obj1, obj2) in jquery?


I have:

json_object *partialObjToSave = json_tokener_parse(json.c_str());
json_object *root = json_tokener_parse(__buffer.c_str());
json_object_object_add
(root, id.c_str(), partialObjToSave);

but dont work... the code will replace the obj with another obj.

I want this obj:

"myID2": {
    "another": "another 1"
,
    "another22": [ array ],

    ...
}

  into this:
{
    "myID1": {
        "name": "my name 1",
        "image": "my image 2"
    },
    "myID2": {
        "name": "my name 1",
        "image": "my name 2"
    }
}

  result:

{
    "myID1": {
        "name": "my name 1",
        "image": "my image 2"
    },
    "myID2": {
        "name": "my name 1",
        "image": "my name 2"

        "another": "another 1"
,
        "another22": [ array ],

        ...
    }
}



Eric Haszlakiewicz

unread,
Nov 17, 2012, 11:33:35 PM11/17/12
to jso...@googlegroups.com
On Nov 17, 2012 10:05 PM, "Carlos Manuel" <carlito...@gmail.com> wrote:
>
> how can i combine 2 objects like $.extend(true, obj1, obj2) in jquery?
>
> json_object *partialObjToSave = json_tokener_parse(json.c_str());
> json_object *root = json_tokener_parse(__buffer.c_str());
> json_object_object_add(root, id.c_str(), partialObjToSave);
>
> but dont work... the code will replace the obj with another obj.

Yes, that's working like it is supposed to. Sorry, json-c doesn't
currently have an "extend"/"merge" function. If you want to do that
you'll need to get a reference to the myID2 object (using
json_object_object_get(root, "myID2")), then iterate over the fields
of partialObjToSave adding each one as you go.

That shouldn't be too bad if you just need to merge things one level
deep, but it might get tricky if you're trying to merge an entire
hierarchy. (e.g. if the myID2 object in root already has an
"another22" array, and you want the elements from the another22 array
in partialObjToSave to be appended)

This certainly seems like a useful feature to have, so if you happen
to implement this and are feeling generous, donating the code would be
appreciated.

Eric
Reply all
Reply to author
Forward
0 new messages