I am using cJSON to parse a JSON stored in testdata.json
file which looks like this:
{
"text": "HelloWorld!!",
"parameters": [{
"length": 10
},
{
"width": 16
},
{
"height": 16
}
]
}
With the following I can access the text
field.
int main(int argc, const char * argv[]) {
//open file and read into buffer
cJSON *root = cJSON_Parse(buffer);
char *text = cJSON_GetObjectItem(root, "text")->valuestring;
printf("text: %s\n", text);
}
Note: These parameters are dynamic in the sense that there can be more parameters such as volume
, area
, etc depending upon what the JSON file contains. The idea is that I have a struct
containing all these parameters and I have to check whether the parameters provided in the JSON exists or not and set the values accordingly.
The struct
looks like:
typedef struct {
char *path;
int length;
int width;
int height;
int volume;
int area;
int angle;
int size;
} JsonParameters;
I tried to do it like this:
cJSON *parameters = cJSON_GetObjectItem(root, "parameters");
int parameters_count = cJSON_GetArraySize(parameters);
printf("Parameters:\n");
for (int i = 0; i < parameters_count; i++) {
cJSON *parameter = cJSON_GetArrayItem(parameters, i);
int length = cJSON_GetObjectItem(parameter, "length")->valueint;
int width = cJSON_GetObjectItem(parameter, "width")->valueint;
int height = cJSON_GetObjectItem(parameter, "height")->valueint;
printf("%d %d %d\n",length, width, height);
}
This returns Memory access error (memory dumped)
plus I have to state what are the keys. As mentioned, I cannot know what will be the parameters.
How can I store the key-value pairs ("length":10
, "width":16
, "height":16
etc) and how can I check the keys against the valid parameters in JsonParameters
?