DaveGamble / cJSON

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

cJSON_DeleteItemFromArray considers dicts and arrays equally #827

Open tregua87 opened 4 months ago

tregua87 commented 4 months ago

I noticed the function cJSON_DeleteItemFromArray does not distinguish between arrays and dicts. Check this example:

int main(int argc, char** argv) {
    cJSON *cjson_0 = nullptr;

    char *x = "{\"\": 992222.22222}";

    cjson_0 =  cJSON_Parse(x); 
    if (cjson_0 == 0)
        return 1;
    printf("cjson_0: %s\n", cJSON_Print(cjson_0));
    cJSON_DeleteItemFromArray(cjson_0, 0);
    printf("cjson_0: %s\n", cJSON_Print(cjson_0));
    cJSON_Delete(cjson_0);

    return 0;
}

Produces this output.

cjson_0: {
        "":     992222.22222
}
cjson_0: {
}

cjson_0 is a dictionary, I would expect the function cJSON_DeleteItemFromArray checks the field cJSON->type. Or it is an intended behavior?

mbratch commented 4 months ago

cjson_0 is a dictionary, I would expect the function cJSON_DeleteItemFromArray checks the field cJSON->type. Or it is an intended behavior?

It's not clear whether it is intended behavior,. It seems like a flaw to me, but it's now ingrained behavior so probably risk to change it without risking breaking some existing user code.

Interesting that get_array_item() will return a child object from a parent given an index, but never cares whether it's an array. It just returns the n-th child in the list of children. But get_array_item is only ever called by array-related functions. Same for add_item_to_array. I didn't check all of them, but the array-specific functions I looked at all would also operate on any object with children.