cJson是开源项目,代码位置https://github.com/DaveGamble/cJSON
下载后将cJSON.c和cJSON.h加入自己的工程中,cJson.h中提供了C语言操作Json的api
Json常用数据结构:
1.object:键值对
2.Array:数组
3.String:字符串
4.Number:数字
一个例子:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "cJSON.h"
void main()
{
cJSON * json = cJSON_CreateObject();
cJSON * tmp1 = NULL;
cJSON * tmp2 = NULL;
cJSON * tmp3 = NULL;
cJSON * tmp4 = NULL;
cJSON_AddItemToObject(json, "class", tmp1 = cJSON_CreateObject());
cJSON_AddStringToObject(tmp1, "name", "option222");
cJSON_AddStringToObject(tmp1, "attribute", "add");
cJSON_AddStringToObject(tmp1, "match if", "option a = aa");
cJSON_AddStringToObject(tmp1, "match if", "option be = 1");
char *buf = cJSON_Print(json);
printf("%s\n", buf);
}
编译命令:
[root@1dot1dot1dot1 json]# gcc class.c cJSON.c
执行效果:
[root@1dot1dot1dot1 json]# ./a.out
{
"class": {
"name": "option222",
"attribute": "add",
"match if": "option cm-class = aa",
"match if": "option dhcp-message-type = 1"
}
}
除了直接打印之外, 可以生成Json格式文件,代码如下:
void func()
{
char * char_json = "{\"Merge\":\"hard\"}";
cJSON * json = cJSON_Parse(char_json);
char *buf = NULL;
printf("data:%s\n", buf = cJSON_Print(json));
FILE * fp = fopen("func.json", "w");
fwrite(buf, strlen(buf), 1, fp);
fclose(fp);
free(buf);
cJSON_Delete(json);
}
编译链接执行后,在本目录下生成func.json文件