ibireme / yyjson

The fastest JSON library in C
https://ibireme.github.io/yyjson/doc/doxygen/html/
MIT License
3.04k stars 262 forks source link

Convert yyjson_val to yyjson_mut_val #92

Closed dan-ryan closed 1 year ago

dan-ryan commented 2 years ago

I want to edit a yyjson_val object. So I want to convert it to yyjson_mut_val edit it and then convert it back to yyjson_val.

What's the ideal way to do this?

Clownsw commented 2 years ago

The same question

ibireme commented 2 years ago

yyjson_val is designed to be immutable and it is used to store the result of JSON parsing. yyjson_mut_val is mutable and is used to construct JSON.

Due to the design of the data structure, there is currently only immutable to mutable conversion, see: https://github.com/ibireme/yyjson/blob/master/doc/DataStructure.md

dan-ryan commented 2 years ago

I'm converting over to this json library; the old library allowed me to edit json that I've read. Our library reads in large packets of json, which is versioned. Older versions of the json data have bugs, so before feeding it into our system, we repair the json.

So you cannot add a constructor to yyjson_mut_val and copy yyjson_val data? and one for yyjson_val to copy yyjson_mut_val data? I don't need to make yyjson_val mutable; just able to create new objects.

Clownsw commented 2 years ago

yyjson_val is designed to be immutable and it is used to store the result of JSON parsing. yyjson_mut_val is mutable and is used to construct JSON.

Due to the design of the data structure, there is currently only immutable to mutable conversion, see: https://github.com/ibireme/yyjson/blob/master/doc/DataStructure.md

Can the conversion be achieved by copying the data?

ibireme commented 2 years ago

Added: https://github.com/ibireme/yyjson/commit/3884c6a4857b5d4ec667631174486128342c9c35

// mut_doc -> doc
yyjson_doc *yyjson_mut_doc_imut_copy(yyjson_mut_doc *doc, yyjson_alc *alc);

// mut_val -> doc
yyjson_doc *yyjson_mut_val_imut_copy(yyjson_mut_val *val, yyjson_alc *alc);

This function will recursively traverse the input value twice to create that immutable document, so it's not very fast.

dan-ryan commented 1 year ago

Xcode is picking up a possible null error: https://ibb.co/Dw6bjmt

ibireme commented 1 year ago

Xcode is picking up a possible null error: https://ibb.co/Dw6bjmt

This should be a false positive: if the input JSON contains no strings, buf is NULL, and memcpy will not be executed.

Fixed here: https://github.com/ibireme/yyjson/commit/7c9fdca77adbf303d1c1c72c15e2a4a1af589b96

dan-ryan commented 1 year ago

Great. Warning gone. Looks like this is all working for me.