The library is great. Thanks!
Regards,
Ryan Phillips
I don't quite understand what you're trying to do. You have parsed a
JSON object:
{
"a": {
...
}
}
like this:
json_t *json = json_load_file("/path/to/json", NULL);
Then fetched the object inside the first object:
json_t *a = json_object_get(json, "a");
Now, what do you want to do? Please explain a bit more clearly.
Petri
Hi Petri,
The documentation states that object 'a' is a borrowed reference. What
I need is to basically do a deep copy of object 'a', place it into
json2, and be able to free json1.
I have tweaked the example to perhaps clarify things.
Regards,
Ryan
The code in your example works correctly. The call
json_object_set(json2, "a", a);
increments the reference count of 'a', so 'a' won't be destroyed when
you call
json_decref(json1);
All the other values inside json1 will be destroyed along with json1
itself.
You don't need a deep copy because 'a' will only destroy (decrement
the refcount of its children) when it is destroyed itself.
Do I make things any clearer? :)
Petri
Thanks, that explanation helps.
Regards,
Ryan
Yeah. Ryan's mail also made me think about copying/cloning JSON
values. I think that both shallow and deep copying might be useful.
A deep copy is a new JSON value that has deep copies of the original's
children as its children, i.e. all the values inside objects and
arrays at all depth levels are new references.
A shallow copy is a copy of the first level only, so the children of
objects and arrays are just references to the original's children.
Obviously, shallow and deep copies make difference only for objects
and arrays, simple values are always fully copied.
I can think of two possible APIs. Either
json_t *json_copy(json_t *json, int deep);
which makes a shallow copy if deep = 0 and a deep copy if deep = 1, or
json_t *json_copy(json_t *json);
json_t *json_deep_copy(json_t *json);
i.e. separate functions for shallow and deep copying. Perhaps the
latter is better.
>
> But references should probably be cleared in the copy, otherwise it
> might be weird or?
> I think of a json_copy function having the same functionality as this:
> char *dump = json_dumps(root1, 0);
> root2 = json_loads(dump, &error);
>
> Or perhaps this was the way to do a deep copy of a json structure ;-)?
> /Martin
Heh, this is obviously the easiest way. But I believe not the most
effective :)
Petri