在C語言中解析json配置檔案
業務需求
在C或者C++專案中常常需要解析配置檔案,我們常見的配置檔案格式一般就是.ini,xml,lua或者是一般的text檔案,這些格式比較惱人的一個問題就是資料格式過於冗餘,或者功能不夠強大,不支援正則匹配,或者實現解析檔案的程式碼過多,效率不高等等。比較大型的開源專案,比如Nginx,ATS等都有自己比較龐大的配置檔案格式,特別是Nginx,語言十分獨特簡潔,功能強大,但是往往程式碼較為繁雜。那麼有沒有比較簡潔的資料交換格式呢?我想到了web上常用到的json格式,這種檔案格式非常簡潔,而且正在日益成為新的交換格式的標準。為此,我打算在我的專案中使用json作為配置檔案。
有沒有一種輕量級的,簡潔夠用的解析實現程式碼,來完成解析json資料的工作呢?
cJSON簡介:
JSON(JavaScriptObject Notation)是一種輕量級的資料交換格式。它基於JavaScript的一個子集。JSON採用完全獨立於語言的文字格式,但是也使用了類似於C語言家族的習慣。這些特性使JSON成為理想的資料交換語言。易於人閱讀和編寫,同時也易於機器解析和生成。
cJSON是一個超輕巧,攜帶方便,單檔案,簡單的可以作為ANSI-C標準的JSON解析器。
cJSON結構體:
typedefstruct cJSON {
structcJSON *next,*prev;
struct cJSON *child;
int type;
char * valuestring;
int valueint;
double valuedouble;
char *string;
}cJSON;
1、cJSON儲存的時候是採用連結串列儲存的,其訪問方式很像一顆樹。每一個節點可以有兄妹節點,通過next/prev指標來查詢,它類似雙向連結串列;每個節點也可以有孩子節點,通過child指標來訪問,進入下一層。
不過,只有節點是物件或陣列才可以有孩子節點。
2、type一共有7種取值,分別是:
#define cJSON_False 0
#define cJSON_True 1
#define cJSON_NULL 2
#define cJSON_Number 3
#define cJSON_String 4
#define cJSON_Array 5
#define cJSON_Object 6
若是Number型別,則valueint或valuedouble中儲存著值,若你期望的是int,則訪問valueint,若期望的是double,則訪問valuedouble,可以得到值。
若是String型別的,則valuestring中儲存著值,可以訪問valuestring得到值。
3、string中存放的是這個節點的名字。
用法:
1、只需在函式中includecJSON.h標頭檔案,然後和cJSON.c或庫檔案libcJSON.a一起編譯即可使用。
2、具體函式用法詳見cJSON.h中註釋。
4.主要函式說明
extern cJSON *cJSON_Parse(const char *value);//解析一個json字串為cJSON物件
extern char *cJSON_Print(cJSON *item);//將json物件轉換成容易讓人看清結構的字串
extern char *cJSON_PrintUnformatted(cJSON *item);//將json物件轉換成一個很短的字串,無回車
extern void cJSON_Delete(cJSON *c);//刪除json物件
extern int cJSON_GetArraySize(cJSON *array);//返回json陣列大小
extern cJSON *cJSON_GetArrayItem(cJSON *array,int item);//返回json陣列中指定位置物件
extern cJSON *cJSON_GetObjectItem(cJSON *object,const char *string);//返回指定字串對應的json物件
extern cJSON *cJSON_CreateIntArray(int *numbers,int count);//生成整型陣列json物件
extern void cJSON_AddItemToArray(cJSON *array, cJSON *item);//向陣列中新增元素
5.使用方法(c語言解析json資料)
先看json的資料結構
c中沒有物件,所以json資料是採用連結串列儲存的
typedef struct cJSON {
struct cJSON *next,*prev; // 陣列 物件資料中用到
struct cJSON *child; // 陣列 和物件中指向子陣列物件或值
int type; // 元素的型別,如是物件還是陣列
char *valuestring; // 如果是字串
int valueint; // 如果是數值
double valuedouble; // 如果型別是cJSON_Number
char *string; // The item's name string, if this item is the child of, or is in the list of subitems of an object.
} cJSON;
比如你有一個json資料
Javascript程式碼
{
"name": "Jack (\"Bee\") Nimble",
"format": {
"type": "rect",
"width": 1920,
"height": 1080,
"interlace": false,
"frame rate": 24
}
}
那麼你可以
1:講字串解析成json結構體。
cJSON *root = cJSON_Parse(my_json_string);
2:獲取某個元素
cJSON *format = cJSON_GetObjectItem(root,"format");
int framerate = cJSON_GetObjectItem(format,"frame rate")->valueint;
3:講json結構體轉換成字串
char *rendered=cJSON_Print(root);
4:刪除
cJSON_Delete(root);
5:構建一個json結構體
cJSON *root,*fmt;
root=cJSON_CreateObject();
cJSON_AddItemToObject(root, "name", cJSON_CreateString("Jack (\"Bee\") Nimble"));
cJSON_AddItemToObject(root, "format", fmt=cJSON_CreateObject());
cJSON_AddStringToObject(fmt,"type", "rect");
cJSON_AddNumberToObject(fmt,"width", 1920);
cJSON_AddNumberToObject(fmt,"height", 1080);
cJSON_AddFalseToObject (fmt,"interlace");
cJSON_AddNumberToObject(fmt,"frame rate", 24);
6.需要澄清的問題
1)cJSON無法區分Object還是Array,它只能通過cJSON中的type欄位做區分,這種原始碼中更能明顯看出
2)對外提供的幾個介面
/* Get Array size/item / object item. */
int cJSON_GetArraySize(cJSON *array) {cJSON *c=array->child;int i=0;while(c)i++,c=c->next;return i;}
cJSON *cJSON_GetArrayItem(cJSON *array,int item) {cJSON *c=array->child; while (c && item>0) item--,c=c->next; return c;}
cJSON *cJSON_GetObjectItem(cJSON *object,const char *string) {cJSON *c=object->child; while (c && cJSON_strcasecmp(c->string,string)) c=c->next; return c;}
返回的cJSON指標,我們無須再釋放;同時
cJSON_GetArraySize返回的是當前子物件陣列的大小,如果還有更深的巢狀層次,不考慮;
cJSON_GetArrayItem返回的是下一級子陣列中,第item個子陣列所在的cJSON物件;
cJSON_GetObjectItem返回的是下一級子物件陣列中,名為string的那個子cJSON物件;
如果我們想找第3層的某個名為string的物件,那隻能一層一層的遍歷,逐層查詢,所以有時候不是很方便,具體做法如
cJSON *format = cJSON_GetObjectItem(root,"format");
int framerate = cJSON_GetObjectItem(format,"frame rate")->valueint;
為此,我們寫如下函式,去遞迴查詢指定名稱的子物件
cJSON* find_Object(cJSON* object, const char* key){
cJSON* subitem = object->child;
while(subitem){
//忽略大小寫進行比較
if(!strcasecmp(subitem->string,key))
return subitem;
//有子節點就優先查詢子節點
cJSON* tmp = NULL;
if(subitem->child)
tmp = find_Object(subitem,key);
if(tmp) return tmp;
//如果子節點沒有找到,返回在本層級查詢
subitem = subitem->next;
}
return subitem;
}
3)修改某個子物件的stringvalue值,恐怕不能直接象修改整數的值這樣做吧,因為字串長度會有變化的,而該物件的記憶體事先已經分配好了
This is an object. We're in C. We don't have objects. But we do have structs.What's the framerate?
cJSON *format = cJSON_GetObjectItem(root,"format");
int framerate = cJSON_GetObjectItem(format,"frame rate")->valueint;
Want to change the framerate?
cJSON_GetObjectItem(format,"frame rate")->valueint=25;
物件的valuestring和string不能修改,只能直接獲取,不需要刪除,比如
void dump_level_1(cJSON* item){
int i;
for(i=0;i<cJSON_GetArraySize(item);i++){
cJSON* subitem = cJSON_GetArrayItem(item,i);
//這裡只能拿到subitem->string,另一個值為空,注意這種方法獲取的都是沒有雙引號的
printf("%s: %s\n",subitem->string,subitem->valuestring);
}
}
另外可參見
http://diaorui.net/archives/245