C语言实现的json解析程序

介绍了一个用C语言实现的JSON解析器,它将JSON文件解析为由互相关联的结构组成的双向循环链表,包括字符串、数字、对象、数组、布尔和null六种类型。为了提高解析效率,采用了内存池设计。

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

只有一个头文件和一个源文件,仅使用C语言标准库。

作用就是读取json文件,然后解析为若干个互相关联的结构,结构如下:

typedef enum json_st {
	djson_string = 1,
	djson_number,
	djson_object,
	djson_array,
	djson_bool,
	djson_null
}json_st;

struct js {//json字符串
	//环链
	void* next;
	json_st nexttype;
	void* prev;
	json_st prevtype;

	json_st type;//此结构类型
	char* key;
	size_t keylen;
	char* str;
	size_t strlen;
};

struct jn {//数字
	//环链
	void* next;
	json_st nexttype;
	void* prev;
	json_st prevtype;

	json_st type;//此结构类型
	char* key;
	size_t keylen;
	double num;//使用double型来储存数值,使用时自行转换

};

struct ja {//数组
	//环链
	void* next;
	json_st nexttype;
	void* prev;
	json_st prevtype;

	json_st type;//此结构类型
	char* key;
	size_t keylen;
	void* array;//数组指针
	size_t arraylen;//数组元素数量
};

struct jb {//布尔
		//环链
	void* next;
	json_st nexttype;
	void* prev;
	json_st prevtype;

	json_st type;//此结构类型
	char* key;
	size_t keylen;
	char bol;//0表示flase,1表示true
};

struct je {//null空
	//环链
	void* next;
	json_st nexttype;
	void* prev;
	json_st prevtype;

	json_st type;//此结构类型
	char* key;
	size_t keylen;
};

struct jo {//json对象
	//环链
	void* next;
	json_st nexttype;
	void* prev;
	json_st prevtype;

	json_st type;//此结构类型
	char* key;
	size_t keylen;

	void* value;//指向包含的项
	json_st value_t;
	int valuenum;
};

json的6种类型分别对应了上述6种结构,其实可以做的更简单一点的,但我懒。

将一个json文件整体看作一个json对象,对象内部的每一项组成一个双向循环链表,以此来确定这些项处于同一级。

为了保证解析速度,采用了内存池设计,一次性获取较大的内存,然后在此内存池中获取内存,避免反复访问系统函数造成多余的开销。

代码草稿见:

https://github.com/lindorx/djson

 

测试结果,右边是原json文件内容,左边是解析json以后再打印的字符串

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值