Closed dan-ryan closed 1 year 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));
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")
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?
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.
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.
Thanks, my testing shows this works great.
What's the best way to rename a key in a json object?