在C語言中,如果要處理多層的JSON數據,我們通常可以使用第三方庫,例如json-c。本文將介紹如何使用json-c庫處理多層JSON數據。
首先,我們需要加載json-c頭文件:
#include <json-c/json.h>
接下來,我們需要將JSON字符串解析為json_object對象:
const char *json_string = "{\"name\": \"jack\", \"age\": 21, \"profile\": {\"city\": \"Shanghai\", \"hobbies\": [\"reading\", \"traveling\"]}}"; json_object *root_object = json_tokener_parse(json_string);
現在,我們可以使用json_object_get函數獲取JSON對象中的值:
// 獲取姓名 json_object *name_object = json_object_object_get(root_object, "name"); const char *name = json_object_get_string(name_object); printf("Name: %s\n", name); // 獲取年齡 json_object *age_object = json_object_object_get(root_object, "age"); int age = json_object_get_int(age_object); printf("Age: %d\n", age); // 獲取居住城市 json_object *profile_object = json_object_object_get(root_object, "profile"); json_object *city_object = json_object_object_get(profile_object, "city"); const char *city = json_object_get_string(city_object); printf("City: %s\n", city); // 獲取興趣愛好 json_object *hobbies_object = json_object_object_get(profile_object, "hobbies"); int hobbies_count = json_object_array_length(hobbies_object); for (int i = 0; i < hobbies_count; i++) { json_object *hobby_object = json_object_array_get_idx(hobbies_object, i); const char *hobby = json_object_get_string(hobby_object); printf("Hobby %d: %s\n", i + 1, hobby); }
以上代碼將輸出:
Name: jack Age: 21 City: Shanghai Hobby 1: reading Hobby 2: traveling
最后,我們需要釋放json_object對象的內存:
json_object_put(root_object);
本文介紹了如何使用json-c庫處理多層JSON數據。希望對大家有所幫助。
上一篇python 結束子程序
下一篇python 終端仿真器