cJSON icon indicating copy to clipboard operation
cJSON copied to clipboard

cJSON_DeleteItemFromArray considers dicts and arrays equally

Open tregua87 opened this issue 1 year ago • 1 comments

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?

tregua87 avatar Feb 06 '24 16:02 tregua87

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.

mbratch avatar Feb 18 '24 22:02 mbratch