JSON是一種常用的數(shù)據(jù)交換格式,在C中讀取JSON文本可以使用JSON-C庫進行解析。
首先需要安裝JSON-C庫并包含頭文件:
#include <stdio.h> #include <stdlib.h> #include <json.h>
讀取JSON文件需要先創(chuàng)建一個json文件對象:
json_object *jobj;
并使用json_object_from_file函數(shù)將JSON文件轉(zhuǎn)換為json文件對象:
jobj = json_object_from_file("example.json");
讀取JSON文件中的數(shù)據(jù)需要使用json_object_get函數(shù)和json_object_get_type函數(shù)來獲取數(shù)據(jù)類型:
json_object *name, *age; name = json_object_object_get(jobj, "name"); const char *name_string = json_object_get_string(name); age = json_object_object_get(jobj, "age"); int age_int = json_object_get_int(age);
最后需要記得釋放json對象所占用的內(nèi)存:
json_object_put(jobj);
完整的代碼如下:
#include <stdio.h> #include <stdlib.h> #include <json.h> int main() { json_object *jobj; json_object *name, *age; jobj = json_object_from_file("example.json"); name = json_object_object_get(jobj, "name"); const char *name_string = json_object_get_string(name); age = json_object_object_get(jobj, "age"); int age_int = json_object_get_int(age); printf("Name: %s\n", name_string); printf("Age: %d\n", age_int); json_object_put(jobj); return 0; }