cjson解析一个json文件,文件是一个json嵌套
时间: 2024-03-17 08:42:20 浏览: 180
好的,您可以使用cjson库来解析json文件。首先,您需要安装cjson库并在代码中包含头文件。然后,您可以使用cjson库中提供的函数来解析json文件。
以下是一个简单的示例代码,假设您的json文件名为example.json:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "cJSON.h"
int main() {
// 打开json文件
FILE *fp = fopen("example.json", "r");
if (fp == NULL) {
printf("Error opening file\n");
return 1;
}
// 获取文件长度
fseek(fp, 0, SEEK_END);
long file_size = ftell(fp);
fseek(fp, 0, SEEK_SET);
// 读取文件内容
char *json_content = malloc(file_size + 1);
fread(json_content, 1, file_size, fp);
fclose(fp);
json_content[file_size] = '\0';
// 解析json内容
cJSON *root = cJSON_Parse(json_content);
if (root == NULL) {
printf("Error parsing JSON\n");
return 1;
}
// 获取嵌套的json对象
cJSON *nested_obj = cJSON_GetObjectItemCaseSensitive(root, "nested_obj");
if (nested_obj == NULL) {
printf("Error getting nested object\n");
cJSON_Delete(root);
return 1;
}
// 获取嵌套对象中的值
cJSON *value = cJSON_GetObjectItemCaseSensitive(nested_obj, "key");
if (value == NULL) {
printf("Error getting value\n");
cJSON_Delete(root);
return 1;
}
printf("Value: %s\n", value->valuestring);
// 释放内存
cJSON_Delete(root);
free(json_content);
return 0;
}
```
在这个例子中,我们首先打开json文件,然后获取文件长度并读取文件内容。接下来,我们使用`cJSON_Parse`函数解析json内容,并使用`cJSON_GetObjectItemCaseSensitive`函数获取嵌套对象和值。最后,我们释放内存并关闭文件。
阅读全文
相关推荐


















