關於c語言操作json,cjson還挺好用,許多操作已經幫開發員封裝好了,使用起來很方便。資源下載地址為:http://sourceforge.net/projects/cjson/
在test.c文件中已經有很多例子,看了還不會使用可以直接看cjson.c文件,也不深奧,實際上就是個雙鏈表,然后是對這個雙鏈表進行增刪改查
記錄下這兩天運用到的
現有一個json文件如下:
[
{
"id": "c1",
"option": "install",
"fid": "1"},
{
"id": "p1",
"option": "notinstall",
"fid": "2"
}
]
1. 讀取一個json文件,返回json結構鏈表,注意,這里返回值必須為cJSON*,具體原因看上一篇文章。另外關於json的介紹看,http://www.json.org/json-zh.html
cJSON* GetJsonObject(char* fileName, cJSON* json)
{
long len;
char* pContent;
int tmp;
FILE* fp = Open_File(fileName, "rb+");
if(!fp)
{
return NULL;
}
fseek(fp,0,SEEK_END);
len=ftell(fp);
if(0 == len)
{
return NULL;
}
fseek(fp,0,SEEK_SET);
pContent = (char*) malloc (sizeof(char)*len);
tmp = fread(pContent,1,len,fp);
Close_File(fp);
json=cJSON_Parse(pContent);
if (!json)
{
return NULL;
}
free(pContent);
return json;
}
2 讀取cJSON索引為index的結點某個key值對應的value,索引從0開始
BOOL GetValueString(cJSON* json,int id, char* name, char* param)
{
cJSON* node;
node = cJSON_GetArrayItem(json,id);
if(!node)
{
return FALSE;
}
sprintf(param, "%s", cJSON_GetObjectItem(node, name)->valuestring);
return TRUE;
}
比如讀取id=1,name="name",得到param為"notinstall"
3 生成json文件
void Create_Pkgs(char* option1, char* option2)
{
cJSON *root,*fld;
char *out;
FILE* fp = Open_File(Pkgs_File, "w+");
root=cJSON_CreateArray();
cJSON_AddItemToArray(root,fld=cJSON_CreateObject());
cJSON_AddStringToObject(fld, "id", "c1");
cJSON_AddStringToObject(fld, "option", option1);
cJSON_AddStringToObject(fld, "fid", "1");
cJSON_AddItemToArray(root,fld=cJSON_CreateObject());
cJSON_AddStringToObject(fld, "id", "p1");
cJSON_AddStringToObject(fld, "option", option2);
cJSON_AddStringToObject(fld, "fid", "2");
out=cJSON_Print(root);
fprintf(fp, out);
Close_File(fp);
cJSON_Delete(root);
free(out);
out = NULL;
root = NULL;
}
