2

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?

Sled
  • 18,541
  • 27
  • 119
  • 168
Riko
  • 256
  • 1
  • 5
  • 15
  • Your sample is not valid JSON. Basically, all he backslashes are invalid. Is this an artifcat from copying it from a debugger, which shows strings with C-style escaping? – Codo Nov 07 '16 at 08:31
  • yes, you r right, i copy it from gdb, and when i use the curl to download the data, it's have no "\", it's like this: – Riko Nov 07 '16 at 08:37
  • [{"id":"6792","date":"2010-01-29","name":"Discuz! 6.0.0 cross site scripting"},{"id":"7570","date":"2009-09-17","name":"Discuz! Plugin Crazy Star <= 2.0 (fmid) SQL Injection Vulnerability"},{"id":"7619","date":"2009-09-15","name":"Discuz! JiangHu plugin versions 1.1 and below remote SQL injection"},{"id":"7779","date":"2009-08-25","name":"Discuz 6.0 (2fly_gift.php) Sql Injection Vulnerability"},{"id":"7878","date":"2009-08-19","name":"Discuz! Remote Reset User Password Exploit"}] – Riko Nov 07 '16 at 08:37
  • I hope this may help you, https://github.com/ajithcofficial/ajson – Ajith C Narayanan Feb 24 '20 at 09:59

1 Answers1

8

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.

Codo
  • 75,595
  • 17
  • 168
  • 206
  • Thank you, your solution make me suddenly enlightened and then instantly understand, very grateful. – Riko Nov 07 '16 at 08:55