akheron / jansson

C library for encoding, decoding and manipulating JSON data
http://www.digip.org/jansson/
Other
3.05k stars 808 forks source link

Is it possible to do json_move instead of json_deep_copy in some specific cases. #629

Closed mmaatuq closed 2 years ago

mmaatuq commented 2 years ago

Is it possible to do json_move instead of json_copy/json_deep_copy? Let's say I have a 2 json objects as following person_data = {"name":"John", "age":30, "car":null} and car_data = {"model": "infniti", "model": "EX37", "year": 2013} from which I want to build a new one car_owner = {"name": "John", "model": "infinti"} and I'm not interested in them anymore. right now I'm copying the objects from the 2 above objects to the new one and then call json_decref on them. but I wish if i can move the objects instead of copying them? I hope my question is clear.

Mephistophiles commented 2 years ago

Hmm, how about:

// person_data - {"name":"John", "age":30, "car":null}
// car_owner - {}
json_t *borrowed_data = json_object_get(person_data, "name"); // get the reference to "name" (person_data is "name" owner", refcount=1)

json_object_set(car_owner, "name", borrowed_data); // add "name" to car_owner with increment refcount (refcount=2)
json_object_del(person_data, "name"); // remove "name" from person_data and decrement refcount (refcount=1, car_owner is "name" owner)
mmaatuq commented 2 years ago

I haven't tried it yet, but it looks what i need. thanks @Mephistophiles