c语言 读取json 文件并放入字符中不要多余的乱码
可以使用第三方库cJSON来解析json文件,并将解析结果存储在字符数组中。以下是一个示例代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "cJSON.h"
int main() {
FILE *fp = fopen("data.json", "r"); // 打开json文件
if (fp == NULL) {
printf("Error opening file.\n");
return 1;
}
// 读取文件内容到缓冲区
char buffer[1024];
size_t size = fread(buffer, 1, sizeof(buffer), fp);
fclose(fp);
// 解析json
cJSON *json = cJSON_Parse(buffer);
if (json == NULL) {
printf("Error parsing JSON.\n");
return 1;
}
// 将解析结果转换为字符串
char *json_str = cJSON_Print(json);
printf("%s\n", json_str);
// 释放资源
cJSON_Delete(json);
free(json_str);
return 0;
}
在该代码中,首先打开json文件并读取其内容到缓冲区。然后使用cJSON_Parse函数将json字符串解析为cJSON对象。接下来,使用cJSON_Print函数将cJSON对象转换为字符串并打印出来。最后,释放cJSON对象和字符串的内存空间。
原文地址: https://www.cveoy.top/t/topic/bSIV 著作权归作者所有。请勿转载和采集!