c语言 读取json 文件
要读取JSON文件,可以使用C语言中的第三方库,例如cJSON。以下是一个简单的示例:
#include <stdio.h>
#include <stdlib.h>
#include "cJSON.h"
int main() {
// 打开JSON文件
FILE *fp = fopen("data.json", "r");
if (fp == NULL) {
printf("Failed to open file\n");
return 1;
}
// 读取文件内容
char buffer[1024];
int len = fread(buffer, 1, sizeof(buffer), fp);
fclose(fp);
// 解析JSON
cJSON *root = cJSON_Parse(buffer);
if (root == NULL) {
printf("Failed to parse JSON\n");
return 1;
}
// 读取JSON中的数据
cJSON *name = cJSON_GetObjectItem(root, "name");
if (cJSON_IsString(name)) {
printf("Name: %s\n", name->valuestring);
}
cJSON *age = cJSON_GetObjectItem(root, "age");
if (cJSON_IsNumber(age)) {
printf("Age: %d\n", age->valueint);
}
// 释放资源
cJSON_Delete(root);
return 0;
}
在这个示例中,我们使用了cJSON库来解析JSON文件。首先打开文件,读取文件内容,然后使用cJSON_Parse函数将其解析为一个cJSON对象。我们可以使用cJSON_GetObjectItem函数来获取JSON中的数据,然后使用cJSON_IsString和cJSON_IsNumber函数来检查数据类型,并使用valuestring和valueint属性来获取字符串和数字数据。最后,我们使用cJSON_Delete函数释放资源。
原文地址: https://www.cveoy.top/t/topic/bSGW 著作权归作者所有。请勿转载和采集!