How to clone an object, is that possible?

529 views
Skip to first unread message

Iharob Al Asimi

unread,
Apr 7, 2016, 3:02:51 PM4/7/16
to json-c
In a program I am writing I have an object containing another object, I read from the parent object and then discard it with json_object_put(). How can I keep the original child object or how can I copy it without converting it to a string and reparsing it?

Eric Haszlakiewicz

unread,
Apr 7, 2016, 11:25:44 PM4/7/16
to jso...@googlegroups.com
On Thu, Apr 7, 2016 at 3:02 PM, Iharob Al Asimi <iha...@gmail.com> wrote:

In a program I am writing I have an object containing another object, I read from the parent object and then discard it with json_object_put(). How can I keep the original child object or how can I copy it without converting it to a string and reparsing it?


If you want to keep using the original child object, simply call json_object_get() on the child to increment its reference count before calling json_object_put() on the parent.

If you really need a copy, sorry there currently isn't an implementation of a copy function, but it's certainly possible to write one, even using just the public API.  Basically, you'd just need to decode the type of the object with json_object_get_type(), call the appropriate json_object_new_* function depending on that, then iterate and recurse for objects of type json_type_object or json_type_array.
Probably the only thing you'd miss using something like that (vs a copy function provided by the library) is keeping anything set by json_object_set_serializer() and perhaps a bit of run-time efficiency.
Of course, if you're optimizing for *programmer* efficiency instead, converting it to a string and reparsing it certainly works. :)

Eric
Reply all
Reply to author
Forward
0 new messages