Closed tomc603 closed 5 months ago
As another work-around, you could find the actual number of strings in your allowed_values
array and pass that as the count parameter instead of the full size of the array. Perhaps a little more convenient than calling cJSON_AddItemToObject
for each actual string.
That said, I do think it would be most convenient if cJSON_CreateStringArray
were smarter. The question would be: what behavior would be most expected?
If all of the pointers after a certain point in the array are NULL, then an obvious approach would be for cJSON_CreateStringArray
to quit adding strings when it sees the first null pointer in the array, or if it has reached the count, whichever comes first.
But what if you pass an array of strings where there are spurious NULL pointers sprinkled throughout the array? Would the expected behavior be then to pluck out the non-null pointers and add those strings in, direct order, to the cJSON array object?
Or perhaps it should put blank (empty) strings in the locations where NULL values occur?
Yeah, these all sound like they have a real chance to break existing code that relies on the existing behavior. Given it's an array of strings, if a change were to be implemented I think iterating through each element to check for NULL is the safest rather than assuming no further items will be valid. But the question of whether to add an empty string or skip the item entirely is probably fraught with edge cases.
I'm absolutely okay with working around the current behavior, because it gives me the most control over behavior. I just wasn't totally sure if there was already a helper somewhere, or if I was missing something more obvious. Thanks for the reply!
I agree. I think cJSON was intended to be a fairly simple or vanilla interface. I've seen a lot of other more special requests go by with different needs for this or that application, but for me, if I need a particular functionality, I just write my own small wrapper function and use that everywhere I need it.
Thanks for the input and advice. I'll close this so it doesn't attract any further attention.
This is perhaps more of a question of intended outcome rather than an issue per se.
I'd like to create a string array from a size capped array of char pointers, but if the entire array isn't populated the
cJSON_CreateStringArray
call returnsNULL
.Is this the intended behavior? Is this perhaps an enhancement that could be made? Obviously if I don't set the array size on definition this all works as expected, but I'm trying to force capping the size of this particular array.
The workaround is that on creation of the JSON string array, I can iterate through the
allowed_values
array, check forNULL
, and callcJSON_AddItemToObject
for each valid string. This isn't a big deal to me, I don't particularly care about needing to work around this behavior, I just wanted to make sure I'm not missing something obvious.