cJson将json文件中数组中的某个变量的值替换然后回写到json文件中的demo
时间: 2024-02-18 13:06:27 浏览: 22
以下是一个示例代码,演示了如何使用cJson将JSON文件中数组中的某个变量的值替换并将其写回到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 *array = cJSON_GetObjectItem(root, "array");
if (array == NULL || !cJSON_IsArray(array)) {
printf("Invalid JSON format\n");
cJSON_Delete(root);
return 1;
}
// 获取需要修改的数组元素
cJSON *element = cJSON_GetArrayItem(array, 1);
if (element == NULL || !cJSON_IsObject(element)) {
printf("Invalid JSON format\n");
cJSON_Delete(root);
return 1;
}
// 替换元素中的值
cJSON_ReplaceItemInObject(element, "value", cJSON_CreateNumber(100));
// 将修改后的JSON对象转换为字符串
char *new_json_str = cJSON_Print(root);
printf("%s\n", new_json_str);
// 将修改后的字符串写回到JSON文件中
fp = fopen("example.json", "wb");
if (fp == NULL) {
printf("Failed to open file\n");
cJSON_Delete(root);
return 1;
}
fwrite(new_json_str, 1, strlen(new_json_str), fp);
fclose(fp);
free(new_json_str);
// 释放内存
cJSON_Delete(root);
return 0;
}
```
在上面的示例中,我们首先使用`fopen`函数打开JSON文件,然后使用`fread`函数将文件内容读入内存。接下来,我们使用`cJSON_Parse`函数将JSON字符串解析为cJson对象。然后,我们使用`cJSON_GetObjectItem`函数获取需要修改的数组,并使用`cJSON_GetArrayItem`函数获取要修改的数组元素。接下来,我们使用`cJSON_ReplaceItemInObject`函数将元素中的"value"键的值替换为数字100。最后,我们使用`cJSON_Print`函数将修改后的JSON对象转换为字符串,并将其写回到JSON文件中。最后,我们使用`cJSON_Delete`函数释放内存并删除cJson对象。请注意,这只是一个示例代码,实际应用中需要根据实际需要进行修改。