DaveGamble / cJSON

Ultralightweight JSON parser in ANSI C
MIT License
10.68k stars 3.21k forks source link

Add a function cJSON_IsEmpty() #829

Open escherstair opened 7 months ago

escherstair commented 7 months ago

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() https://github.com/DaveGamble/cJSON/blob/87d8f0961a01bf09bef98ff89bae9fdec42181ee/cJSON.c#L1833-L1854

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?

mbratch commented 7 months ago

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.

escherstair commented 7 months ago

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 [].

mbratch commented 7 months ago

@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.

escherstair commented 7 months ago

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