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

Renaming a key #91

Closed dan-ryan closed 1 year ago

dan-ryan commented 2 years ago

What's the best way to rename a key in a json object?

ibireme commented 2 years ago

If your key is a constant string, this function is the simplest:

// use iterator to get the key
yyjson_mut_val *key = ...;  
yyjson_mut_set_str(key, "new_str");

If you want yyjson to manage memory for that string, use this function:

// use iterator to get the key
yyjson_mut_val *old_key = ...;
yyjson_mut_val *new_key = yyjson_mut_strncpy(doc, str, str_len);
yyjson_mut_set_strn(old_key, yyjson_mut_get_str(new_key), yyjson_mut_get_len(new_key));
dan-ryan commented 2 years ago

Oh yyjson_mut_set_str is not in the released lib that's why I missed it. Are you doing an update soon? May I also suggest a method for easily updating keys? Something like: yyjson_mut_key_set_str(doc, root, "oldKey", "newKey")

ibireme commented 2 years ago

I will release a new version around the end of the year. But the master branch is stable, and you can use it now.

The function to rename key seems to be rarely used, can you describe how you would use it?

dan-ryan commented 2 years ago

The function to rename key seems to be rarely used, can you describe how you would use it?

Maybe I'm a special case. I use it to fix broken json before feeding it into our system.

ibireme commented 2 years ago

Added: https://github.com/ibireme/yyjson/commit/e98bf96594bd5e9c9e33b223757c33f92ca4d606

Note that if the object contains the new_key, there may be duplicate keys after renaming. e.g. {"a":1,"b":2} after renaming "a" to "b" -> {"b ":1,"b":2}. You can avoid this by calling yyjson_mut_obj_remove_key() to remove the new_key before renaming.

dan-ryan commented 1 year ago

Thanks, my testing shows this works great.