I am bignner in C and was looking for some simple json api in C and found this the simplest of all. So, thanks for that.
Now, the problem. I am obviously trying to parse the json to an struct. What I am trying to do is to get the item name in the loop instead of hardcoding like in cJSON_GetObjectItem(record,"domain")->valuestring. I understand that there's no direct api to fetch the item names so what I tried my best to understand the cJSON and came up with this:
intparse_json_to_result(char*json,db_res_t**result){cJSON*root,*record;intrecourdCount=0;inti=0;intvalue=0;intint_val=0;char*str_val='\0';root=cJSON_Parse(json);recourdCount=cJSON_GetArraySize(root);printf("arraysize:%d\n", recourdCount); *result = malloc(sizeof(db_res_t)); (*result)->rows =malloc(sizeof(db_row_t)*recourdCount); for(i=0;i<recourdCount;i++) { record = cJSON_GetArrayItem(root, i); (*result)->rows[i].values = malloc(sizeof(db_val_t)); cJSON *subitem = record-> child; while(subitem) {//This works fine for null. printf("domain:%s\n",cJSON_GetObjectItem(record,"domain")->valuestring);//This fails if value is null. // printf("%s\t:",subitem->string); if(subitem->type == cJSON_Number) { int_val = cJSON_GetObjectItem(record,subitem->string)->valueint; printf("%d\n",int_val); (*result)->rows[i].values->val.int_val = int_val; } else { str_val = cJSON_GetObjectItem(record,subitem->string)->valuestring; printf("%s\n",str_val);(*result)->rows[i].values->val.str_val.s=str_val;}subitem=subitem->next;}}free(root);return1;}
Above code works as expected until it encounters values which are null. "" [{"username":"ubuntu","domain":"192.168.254.129"}] // this works [{"username":"ubuntu","domain":""}] // this works [{"username":"ubuntu","domain":null}] // this fails
Is this the expected behaviour or I am missing something in the code?
I tried to understand in the code but I am still not that expert in C to understand this code. Please help me here.
Thanks
If you would like to refer to this comment somewhere else in this project, copy and paste the following link:
I am bignner in C and was looking for some simple json api in C and found this the simplest of all. So, thanks for that.
Now, the problem. I am obviously trying to parse the json to an struct. What I am trying to do is to get the item name in the loop instead of hardcoding like in cJSON_GetObjectItem(record,"domain")->valuestring. I understand that there's no direct api to fetch the item names so what I tried my best to understand the cJSON and came up with this:
Above code works as expected until it encounters values which are null. ""
[{"username":"ubuntu","domain":"192.168.254.129"}] // this works
[{"username":"ubuntu","domain":""}] // this works
[{"username":"ubuntu","domain":null}] // this fails
Is this the expected behaviour or I am missing something in the code?
I tried to understand in the code but I am still not that expert in C to understand this code. Please help me here.
Thanks