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

iterating over objects and adding additional values #883

Closed
offset18 opened this issue Aug 16, 2024 · 1 comment
Closed

iterating over objects and adding additional values #883

offset18 opened this issue Aug 16, 2024 · 1 comment

Comments

@offset18
Copy link

offset18 commented Aug 16, 2024

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.

@offset18
Copy link
Author

offset18 commented Sep 5, 2024

Solved the problem.

@offset18 offset18 closed this as completed Sep 5, 2024
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

1 participant