DaveGamble/cJSON

iterating over objects and adding additional values

offset18 opened this issue · 1 comments

Hello,
i m currently suffering by adding addtional values to an array of objects.
The iteration seems to work somehow,
but i think I have to use the cjson_arrayforeach function differently
or get rid of some loops.
This my experimental code:

` cJSON *json = cJSON_Parse(buffer);
if (json == NULL) {
const char *error_ptr = cJSON_GetErrorPtr();
if (error_ptr != NULL) {
printf("Error: %s\n", error_ptr);
}
cJSON_Delete(json);
return 1;
}

cJSON *iterate = NULL;

cJSON *iterate = NULL;
cJSON_ArrayForEach(iterate,json) {
int count = 0 ;
while(count == 0) {

        cJSON *valuea = cJSON_GetObjectItemCaseSensitive(iterate,"valuea");
        cJSON *valueb = cJSON_GetObjectItemCaseSensitive(iterate, "valueb");
        for(int a = 0; a < cJSON_GetArraySize(json);a++) {

            if(cJSON_IsNumber(valuea)&&cJSON_GetNumberValue(valueb)==58) {

                int va = valuea->valueint;
                int va1 = va >> 8;
                int va2 = va & 256;
                if(a == 0) {
                    cJSON_AddNumberToObject(json->child,"va1",va1);
                    cJSON_AddNumberToObject(json->child,"va2",va2);


                }
                else {
                    cJSON_AddNumberToObject(json->child->next,"va1",va1);
                    cJSON_AddNumberToObject(json->child->next,"va2",va2);

                }
        

            }
        }
        count++;

    }
}

and this what has been added to my json file
[{ "valuea": 5434, "Bytes": 1, "valueb": 58, "va1": 21, "va2": 256, "va1": 240, "va2": 0 }, { "valuea": 61578, "Bytes": 1, "valueb": 58, "va1": 21, "va2": 256, "va1": 21, "va2": 256, "va1": 240, "va2": 0, "va1": 240, "va2": 0 }, { "valuea": 61258, "Bytes": 2, "valueb": 56 }]
I should be just one line va1 & va2 per object.

Many thanks in advance.

Solved the problem.