DaveGamble/cJSON

Add a function cJSON_IsEmpty()

escherstair opened this issue · 4 comments

Sometimes it's require dto check if a JSON object or array is empty.
As far as I understand, this requires looking to json->child, as done inside cJSON_GetArraySize()

cJSON/cJSON.c

Lines 1833 to 1854 in 87d8f09

CJSON_PUBLIC(int) cJSON_GetArraySize(const cJSON *array)
{
cJSON *child = NULL;
size_t size = 0;
if (array == NULL)
{
return 0;
}
child = array->child;
while(child != NULL)
{
size++;
child = child->next;
}
/* FIXME: Can overflow here. Cannot be fixed without breaking the API */
return (int)size;
}

I would suggest adding a new function, as an example:

/* Checks if the object/array is empty. */
CJSON_PUBLIC(cJSON_bool) cJSON_IsEmpty(const cJSON *item)
{
    if (item == NULL)
    {
        return false;
    }
    return (item->child == NULL);
}

What do you think?

I think you can just call cJSON_IsArray or cJSON_IsObject without having to look into the cJSON structure yourself and read child. These functions both return false if the item passed is NULL.

Hi @mbratch,
sorry for the confusion, but I'm not interested in finding if the item is NULL.
I need to detect if it points to an empty json object {} or empty json array [].

@escherstair I see thanks for clarifying, I misunderstood.

I suppose it may be an application-specific need. If it were a common pattern in my application, I'd just write my own little function for it.

If you think it's not a general use case, for me it's ok going on witth the little custom function I wrote.