cJson不改变自己json文件的格式下提换value
时间: 2024-02-18 08:06:23 浏览: 35
你可以使用cJson库来读取和修改JSON文件中的值,而不改变其格式。首先,你需要使用cJson库中的函数将JSON文件读入内存中的cJson对象中。然后,你可以使用cJson提供的函数来获取和修改JSON对象中的值。
以下是一个示例代码,该代码演示了如何使用cJson来读取JSON文件并替换其中的一个值:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "cJSON.h"
int main()
{
// 读取JSON文件
FILE *fp = fopen("example.json", "rb");
if (fp == NULL) {
printf("Failed to open file\n");
return 1;
}
fseek(fp, 0, SEEK_END);
long file_size = ftell(fp);
fseek(fp, 0, SEEK_SET);
char *json_str = (char *)malloc(file_size + 1);
fread(json_str, 1, file_size, fp);
fclose(fp);
// 将JSON文件解析为cJson对象
cJSON *root = cJSON_Parse(json_str);
free(json_str);
// 获取需要修改的值
cJSON *value = cJSON_GetObjectItem(root, "key");
// 替换值
cJSON_ReplaceItemInObject(root, "key", cJSON_CreateString("new_value"));
// 将修改后的JSON对象转换为字符串
char *new_json_str = cJSON_Print(root);
printf("%s\n", new_json_str);
free(new_json_str);
// 释放内存
cJSON_Delete(root);
return 0;
}
```
在上面的示例中,我们首先使用`fopen`函数打开JSON文件,然后使用`fread`函数将文件内容读入内存。接下来,我们使用`cJSON_Parse`函数将JSON字符串解析为cJson对象。然后,我们使用`cJSON_GetObjectItem`函数获取需要修改的值,并使用`cJSON_ReplaceItemInObject`函数将其替换为新值。最后,我们使用`cJSON_Print`函数将修改后的JSON对象转换为字符串,并输出到控制台。最后,我们使用`cJSON_Delete`函数释放内存并删除cJson对象。