DaveGamble / cJSON

Ultralightweight JSON parser in ANSI C
MIT License
10.28k stars 3.15k forks source link

Copy object item key to replacement in ReplaceItemViaPointer #859

Open oantby opened 1 month ago

oantby commented 1 month ago

README indicates that object items can be replaced with cJSON_ReplaceItemViaPointer. However, the key for an object item will be lost in that process, unless the caller uses information on cJSON internals to update the replacement object's key with that of the source. cJSON_ReplaceItemInObject is listed as the other method for replacing an object item, and does set the key on the replacement value. This PR updates cJSON_ReplaceItemViaPointer to copy any string on the item to be replaced with that of the source. Consideration was made to just reuse the string from the item being replaced - opted to effectively replicate the existing functionality of cJSON_ReplaceItemInObject, which always allocated a new string for key.

Example:

    cJSON *j, *r, *t;
    j = cJSON_Parse("{\"foo\": \"bar\"}");
    r = cJSON_Parse("{\"bar\": true}");

    t = cJSON_GetObjectItemCaseSensitive(j, "foo");
    cJSON_ReplaceItemViaPointer(j, t, r);
    puts(cJSON_Print(j));

Under master, this prints:

{
    "": {
        "bar":  true
    }
}

After this PR:

{
    "foo":  {
        "bar":  true
    }
}

Couldn't find contributor guidelines at a glance, so let me know if there are any other specifics needed here.

oantby commented 1 month ago

I found the contributing guidelines, and added this to the unit test for object item replacement.