我們先看一下JSON數據的結構。假設我們有如下一段JSON數據:
{
"person": [
{
"name": "Tom",
"age": 18,
"gender": "Male",
"phone": {
"work": "123456",
"home": "789012"
}
},
{
"name": "Jack",
"age": 22,
"gender": "Male",
"phone": {
"work": "345678",
"home": "901234"
}
}
]
}
我們要篩選出名字為Tom的人的信息。首先,我們需要先解析JSON數據:
cJSON *root = cJSON_Parse(json_string);
if (root == NULL)
{
printf("Error: cJSON_Parse\n");
return;
}
其中,json_string就是我們要解析的JSON字符串。解析成功后,root指針就指向了JSON數據的根節點。
接著,我們需要遍歷person數組找到名字為Tom的人:
cJSON *person_array = cJSON_GetObjectItemCaseSensitive(root, "person");
if (!cJSON_IsArray(person_array))
{
printf("Error: person is not an object\n");
return;
}
int array_size = cJSON_GetArraySize(person_array);
for (int i = 0; i< array_size; i++)
{
cJSON *person = cJSON_GetArrayItem(person_array, i);
cJSON *name = cJSON_GetObjectItemCaseSensitive(person, "name");
if (cJSON_IsString(name) && strcmp(name->valuestring, "Tom") == 0)
{
cJSON *age = cJSON_GetObjectItemCaseSensitive(person, "age");
cJSON *gender = cJSON_GetObjectItemCaseSensitive(person, "gender");
cJSON *phone = cJSON_GetObjectItemCaseSensitive(person, "phone");
cJSON *work_phone = cJSON_GetObjectItemCaseSensitive(phone, "work");
cJSON *home_phone = cJSON_GetObjectItemCaseSensitive(phone, "home");
printf("Name: %s\n", name->valuestring);
printf("Age: %d\n", age->valueint);
printf("Gender: %s\n", gender->valuestring);
printf("Work Phone: %s\n", work_phone->valuestring);
printf("Home Phone: %s\n", home_phone->valuestring);
break;
}
}
以上代碼將會輸出名字為Tom的人的信息。如果要篩選其它條件的數據,只需要修改判斷語句即可。