Riko
Riko

Reputation: 276

How cJSON parse the json array?

I have a question about the C parse the json array, I know how cJSON parse the json use C, but I can't find any result in Google about how to parse the json array, I have watched the Using cJSON to read in a JSON array, but it doesn't suit me.

I recive a json array from web API and it look like this:

[{\"id\":\"25139\",\"date\":\"2016-10-27\",\"name\":\"Komfy Switch With Camera DKZ-201S\\/W Password Disclosure\"},{\"id\":\"25117\",\"date\":\"2016-10-24\",\"name\":\"NETDOIT weak password Vulnerability\"}]

As you see, there are many json in a array, so, how can i parse the array with cJSON lib?

Upvotes: 2

Views: 11757

Answers (1)

Codo
Codo

Reputation: 78975

cJSON supports the full range, i.e. both JSON arrays and objects. When accessing the data, you just need to understand what the type of the current piece is.

In your case, it's an array containing objects containg simple values. So this is how you handle it:

int i;
cJSON *elem;
cJSON *name;
char *json_string = "[{\"id\":\"25139\",\"date\":\"2016-10-27\",\"name\":\"Komfy Switch With Camera DKZ-201S\\/W Password Disclosure\"},{\"id\":\"25117\",\"date\":\"2016-10-24\",\"name\":\"NETDOIT weak password Vulnerability\"}]";
cJSON *root = cJSON_Parse(my_json_string);
int n = cJSON_GetArraySize(root);
for (i = 0; i < n; i++) {
    elem = cJSON_GetArrayItem(root, i);
    name = cJSON_GetObjectItem(elem, "name");
    printf("%s\n", name->valuestring);
}

I haven't compiled it. I hope it's not too far off.

Upvotes: 8

Related Questions