使用cJSON库更新json文件

前端之家收集整理的这篇文章主要介绍了使用cJSON库更新json文件前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

测试程序的目的是更新已有的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,SEEK_END);
	len=ftell(f);
	fseek(f,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 = dofile("basicparameter.cfg");
	out = cJSON_Print(root);
	printf("before modify:%s\n",out);
	free(out);
	basicpara = cJSON_GetObjectItem(root,"basicparameter");
	cJSON_GetObjectItem(basicpara,"mode")->valueint = 0;
	//cJSON_GetObjectItem(basicpara,"mode")->valuedouble = 0;
	cJSON_GetObjectItem(basicpara,"TimeoutPoweron")->valueint = 10;
	//cJSON_GetObjectItem(basicpara,"TimeoutPoweron")->valuedouble = 10;

	out = cJSON_Print(root);
	printf("after modify:%s\n",out);
	free(out);
	//write_file("basicparameter.cfg",out);
	cJSON_Delete(root);

	return 0;
}

刚开始只修改了valueint的值,结果显示修改前后的结果一样。

cJSON_GetObjectItem(basicpara,"mode")->valueint = 0;


然后修改valuedouble的值,才能真能修改json文件


如果只调用

cJSON_GetObjectItem(basicpara,"mode")->valuedouble = 0;
也只是修改了valuedouble的值。

所以如果想要修改valueint的值必须同时调用

cJSON_GetObjectItem(basicpara,"mode")->valueint = 0;
cJSON_GetObjectItem(basicpara,"mode")->valuedouble = 0;
 引用链接https://sourceforge.net/p/cjson/discussion/998970/thread/5c13b93f/ 原文链接:https://www.f2er.com/json/289444.html

猜你在找的Json相关文章