只有一個頭文件和一個源文件,僅使用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以後再打印的字符串