使用cJSON库更新json文件

这篇博客探讨了如何利用cJSON库来更新现有的json文件。通过测试代码示例,作者指出仅修改valueint的值无法实际更新文件,而需要同时修改valuedouble的值才能确保json文件被正确修改。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

测试程序的目的是更新已有的json文件。

下面是测试程序的代码

#include "smartlight.h"
#include "cJSON.h"

cJSON *dofile(char *filename)
{
	FILE *f;
	long len;
	char *data;
	cJSON *json,*ret;
	
	f=fopen(filename,"rb");
	fseek(f,0,SEEK_END);
	len=ftell(f);
	fseek(f,0,SEEK_SET);
	data=(char*)malloc(len+1);
	fread(data,1,len,f);
	data[len]='\0';
	json=cJSON_Parse(data);
	if (!json) 
	{
		printf("Error before: [%s]\n",cJSON_GetErrorPtr());
		ret = NULL;
		goto EXIT;
	}
	else
	{
		//printf("%s\n",data);
		ret = json;
	}

EXIT:
	free(data);
	fclose(f);
	return ret;
}

int write_file(char *filename,char *out)
{
	FILE *fp = NULL;

	fp = fopen(filename,"a+");
	if(fp == NULL)
	{
		fprintf(stderr,"open file failed\n");
		exit(-1);
	}
	fprintf(fp,"%s",out);

	if(fp != NULL)
		fclose(fp);
}

int main()
{
	cJSON *root,*basicpara;
	char *out;

	root
在C语言中,使用cJSON可以方便地处理JSON数据并将其写入文件。首先,你需要包含必要的头文件,并初始化。以下是写入JSON文件的一个简单示例: ```c #include "cJSON.h" #include <stdio.h> #include <string.h> // 示例JSON数据结构 typedef struct { const char *name; int age; } Person; void write_json_to_file(const cJSON *root, const char *filename) { FILE *file = fopen(filename, "w"); if (!file) { printf("Error opening file %s\n", filename); return; } // 将 cJSON 树转换为字符串 char *json_string = cJSON_Print(root); if (json_string == NULL) { printf("Error converting JSON to string\n"); fclose(file); return; } // 写入文件 fprintf(file, "%s", json_string); // 清理内存 free(json_string); // 关闭文件 fclose(file); } int main() { // 创建一个Person对象 Person person = {"John Doe", 30}; // 使用cJSON创建JSONcJSON *root = cJSON_CreateObject(); cJSON_AddStringToObject(root, "name", person.name); cJSON_AddNumberToObject(root, "age", person.age); // 将JSON树写入文件 write_json_to_file(root, "person.json"); // 清理cJSON cJSON_Delete(root); return 0; } ``` 在这个例子中,我们首先创建了一个`Person`结构体和一个空的对象作为根。然后添加了一些键值对到这个对象中,最后将整个JSON对象写入名为"person.json"的文件。 注意,记得在项目中包含cJSON,通常通过`git clone`或者直接下载源码并在编译时链接到你的项目中。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值