如果在解析JSON数据时不知道键的名称或值的数据类型,可以使用cJSON库中的一些函数来处理。
下面是一个示例代码,使用cJSON库来解析一个JSON数据,其中包含未知键和值:
#include
#include
#include "cJSON.h"
int main()
{
char *json_string = "{\"key1\":\"value1\",\"key2\":2}";
cJSON *root = cJSON_Parse(json_string);
if (root == NULL)
{
printf("Error before: [%s]\n", cJSON_GetErrorPtr());
return 1;
}
cJSON *item = NULL;
cJSON_ArrayForEach(item, root)
{
switch (item->type)
{
case cJSON_String:
printf("string: %s\n", item->valuestring);
break;
case cJSON_Number:
printf("number: %d\n", item->valueint);
break;
default:
printf("unknown type\n");
break;
}
}
cJSON_Delete(root);
return 0;
}
在此示例中,使用cJSON_Parse函数将JSON字符串解析为cJSON对象。然后,使用cJSON_ArrayForEach函数来遍历对象中的每个键值。在此过程中,使用switch语句检查值的数据类型,并据此执行相应的操作。
例如,如果值是字符串,则使用cJSON对象的valuestring成员来访问该字符串。如果该值是数字,则使用valueint成员。在本示例中,未知类型的值被视为“unknown type”。