Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a function cJSON_IsEmpty() #829

Open
escherstair opened this issue Feb 12, 2024 · 4 comments
Open

Add a function cJSON_IsEmpty() #829

escherstair opened this issue Feb 12, 2024 · 4 comments

Comments

@escherstair
Copy link

escherstair commented Feb 12, 2024

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?

@mbratch
Copy link

mbratch commented Feb 12, 2024

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
Copy link
Author

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
Copy link

mbratch commented Feb 12, 2024

@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
Copy link
Author

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants