JSON是一種輕量級的數(shù)據(jù)交換格式,它在互聯(lián)網(wǎng)應(yīng)用中被廣泛使用。在C編程語言中,我們可以通過第三方JSON庫來解析和生成JSON數(shù)據(jù)。
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <jansson.h> int main() { char *json_string = "{\"name\":\"Tom\",\"age\":20,\"score\":{\"chinese\":90,\"math\":80,\"english\":85}}"; json_t *json; json_error_t error; json = json_loads(json_string, 0, &error); if (!json) { fprintf(stderr, "Error parse json: %s\n", error.text); return EXIT_FAILURE; } const char *name = json_string_value(json_object_get(json, "name")); int age = json_integer_value(json_object_get(json, "age")); printf("name: %s, age: %d\n", name, age); json_t *score = json_object_get(json, "score"); int chinese = json_integer_value(json_object_get(score, "chinese")); int math = json_integer_value(json_object_get(score, "math")); int english = json_integer_value(json_object_get(score, "english")); printf("chinese: %d, math: %d, english: %d\n", chinese, math, english); json_decref(json); return EXIT_SUCCESS; }
上面的代碼演示了如何使用json_loads函數(shù)將JSON字符串解析為一個json_t對象,并根據(jù)Key值獲取對應(yīng)的Value值。
除了解析JSON數(shù)據(jù),我們也可以通過JSON庫來生成JSON數(shù)據(jù):
json_t *root, *score_obj; root = json_object(); json_object_set_new(root, "name", json_string("Tom")); json_object_set_new(root, "age", json_integer(20)); score_obj = json_object(); json_object_set_new(score_obj, "chinese", json_integer(90)); json_object_set_new(score_obj, "math", json_integer(80)); json_object_set_new(score_obj, "english", json_integer(85)); json_object_set(root, "score", score_obj); char *json_string = json_dumps(root, JSON_INDENT(4)); printf("%s", json_string); json_decref(score_obj); json_decref(root); free(json_string);
上面的代碼創(chuàng)建了一個json_t對象,根據(jù)Key值分別添加不同類型的Value值,并調(diào)用json_dumps函數(shù)將該JSON數(shù)據(jù)轉(zhuǎn)換成JSON格式的字符串。