Need something more than cJSON_GetStringValue for an array
Consider a JSON array that looks like the following:
"ArrayName" : [ 1, 2, 3 ]
Now you want to reference each of these objects. You have at your disposal, as recommended, the cJSON_ArrayForEach() macro, which returns a cJSON element. Now what do you do? If the array elements were strings, you would just do cJSON_GetStringValue(element). But you want the number (or whatever type your array is; imagine if it's nested). My suggestion: add appropriate convenience macros that match cJSON_Is{...}.
hi, i don't know if you or anyone else needs this, but i encountered the same problem today and i found a solution so you can read items from an array or item from in object inside an array, well, first let's consider this json format :
{
"firstName": "John",
"lastName": "Smith",
"isAlive": true,
"age": 27,
"address": {
"streetAddress": "21 2nd Street",
"city": "New York",
"state": "NY",
"postalCode": "10021-3100"
},
"phoneNumbers": [
{
"type": "home",
"number": "212 555-1234"
},
{
"type": "office",
"number": "646 555-4567"
}
],
"children": [],
"spouse": null
}
we will concentrate on the phoneNumbers array :
all you need to do is use a for loop but first
this is the code i use to read data from any array:
cJSON *root = cJSON_Parse((char*)buf);
cJSON *phoneNumbers = cJSON_GetObjectItemCaseSensitive(root, "phoneNumbers");
int temp_n = cJSON_GetArraySize(phoneNumbers);
for (int i =0; i<temp_n; i++)
{
cJSON *temp1 = cJSON_GetArrayItem(phoneNumbers, i);
cJSON *type = cJSON_GetObjectItemCaseSensitive(temp1, "type");
fprintf(stderr,"cronTemplate: %s\n", cJSON_Print(type));
cJSON *number = cJSON_GetObjectItemCaseSensitive(temp1, "number");
fprintf(stderr,"operation: %s\n", cJSON_Print(number));
}
hope this helps anyone!