文档似乎是一个很好的起点。这是一个最低限度可重复的答案:
#include <stdio.h>
#include "cJSON.h"
const char *myJsonString = "{" \
" \"details\": [ " \
" { " \
" \"person1\": [ " \
" { " \
" \"name\": \"xxx\", " \
" \"strength\": \"abc\" " \
" } " \
" ], " \
" \"person2\": [ " \
" { " \
" \"name\": \"yyy\", " \
" \"strength\": \"def\" " \
" } " \
" ], " \
" \"person3\": [ " \
" { " \
" \"name\": \"zzz\", " \
" \"strength\": \"abc\" " \
" } " \
" ] " \
" } " \
" ] " \
"}";
int main()
{
cJSON *root = cJSON_Parse(myJsonString);
cJSON *details = cJSON_GetObjectItem(root, "details");
int detailsIndex;
for (detailsIndex = 0; detailsIndex < cJSON_GetArraySize(details); detailsIndex++) {
cJSON *people = cJSON_GetArrayItem(details, detailsIndex);
int personIndex;
for (personIndex = 0; personIndex < cJSON_GetArraySize(people); personIndex++) {
cJSON *personItems = cJSON_GetArrayItem(people, personIndex);
const char *personKeyName = personItems->string;
int itemIndex;
for (itemIndex = 0; itemIndex < cJSON_GetArraySize(personItems); itemIndex++) {
cJSON *personItem = cJSON_GetArrayItem(personItems, itemIndex);
const char *name = cJSON_GetObjectItem(personItem, "name")->valuestring;
const char *strength = cJSON_GetObjectItem(personItem, "strength")->valuestring;
fprintf(stderr, "personKeyName [%s] name [%s] strength [%s]\n", personKeyName, name, strength);
}
}
}
cJSON_Delete(root);
return 0;
}
编译:
$ wget -qO- https://raw.githubusercontent.com/insertion/cJOSN/master/cJSON.c > cJSON.c
$ wget -qO- https://raw.githubusercontent.com/insertion/cJOSN/master/cJSON.h > cJSON.h
$ gcc -Wall cJSON.c test.c -o test -lm
跑步:
$ ./test
personKeyName [person1] name [xxx] strength [abc]
personKeyName [person2] name [yyy] strength [def]
personKeyName [person3] name [zzz] strength [abc]