在C語言中,可以使用JSON(JavaScript Object Notation)來存儲和傳輸數據。
JSON是一種輕量級的文本數據格式,具有良好的可讀性和易于使用的特性。它由鍵-值對組成,用逗號分隔,并通過大括號封裝。值可以是字符串、數字、布爾值、數組和對象。
{ "name": "張三", "age": 25, "married": false, "hobbies": ["籃球", "游泳", "唱歌"], "address": { "province": "廣東", "city": "深圳", "street": "科技南路" } }
在C中,可以使用第三方庫來解析和生成JSON數據。常用的庫有cJSON和Jansson。
cJSON是一個輕量級的JSON解析器,具有良好的可移植性和易于使用的API。它的數據結構也是由鍵-值對組成,用指針鏈接,并通過結構體封裝。成員可以是字符串、數字、布爾值、數組和對象。
#include#include #include "cJSON.h" int main() { cJSON *json = cJSON_CreateObject(); cJSON_AddStringToObject(json, "name", "張三"); cJSON_AddNumberToObject(json, "age", 25); cJSON_AddBoolToObject(json, "married", 0); cJSON *hobbies = cJSON_CreateArray(); cJSON_AddItemToArray(hobbies, cJSON_CreateString("籃球")); cJSON_AddItemToArray(hobbies, cJSON_CreateString("游泳")); cJSON_AddItemToArray(hobbies, cJSON_CreateString("唱歌")); cJSON_AddItemToObject(json, "hobbies", hobbies); cJSON *address = cJSON_CreateObject(); cJSON_AddStringToObject(address, "province", "廣東"); cJSON_AddStringToObject(address, "city", "深圳"); cJSON_AddStringToObject(address, "street", "科技南路"); cJSON_AddItemToObject(json, "address", address); char *data = cJSON_Print(json); printf("%s\n", data); cJSON_Delete(json); free(data); return 0; }
Jansson也是一個輕量級的JSON庫,具有高性能和可擴展性,支持JSON的各種功能(如Unicode轉義、數字精度和枚舉類型)。它的數據結構也是由鍵-值對組成,用指針鏈接,并通過結構體封裝。成員可以是字符串、數字、布爾值、數組和對象。
#include#include int main() { json_t *json = json_object(); json_object_set_new(json, "name", json_string("張三")); json_object_set_new(json, "age", json_integer(25)); json_object_set_new(json, "married", json_false()); json_t *hobbies = json_array(); json_array_append_new(hobbies, json_string("籃球")); json_array_append_new(hobbies, json_string("游泳")); json_array_append_new(hobbies, json_string("唱歌")); json_object_set_new(json, "hobbies", hobbies); json_t *address = json_object(); json_object_set_new(address, "province", json_string("廣東")); json_object_set_new(address, "city", json_string("深圳")); json_object_set_new(address, "street", json_string("科技南路")); json_object_set_new(json, "address", address); char *data = json_dumps(json, JSON_INDENT(4)); printf("%s\n", data); json_decref(json); free(data); return 0; }