只有一个头文件和一个源文件,仅使用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以后再打印的字符串