在C語言中,有時(shí)需要將數(shù)據(jù)以JSON的格式輸出,以方便后續(xù)的處理。本文將介紹如何將C List轉(zhuǎn)換為JSON格式。
首先需要導(dǎo)入json-c庫,代碼如下:
#include "json-c/json.h"
接著,定義一個(gè)函數(shù)將C List轉(zhuǎn)換為JSON字符串:
char* list_to_json_string(struct list_head* list) { struct list_head* pos; char* result; int i = 0; struct json_object* array = json_object_new_array(); list_for_each(pos, list) { struct json_object* object = json_object_new_object(); struct node* node = list_entry(pos, struct node, list); json_object_object_add(object, "id", json_object_new_int(node->id)); json_object_object_add(object, "name", json_object_new_string(node->name)); json_object_object_add(object, "age", json_object_new_int(node->age)); json_object_array_add(array, object); i++; } result = strdup(json_object_to_json_string(array)); json_object_put(array); return result; }
上述代碼中,我們使用了json_object_new_array和json_object_new_object函數(shù)創(chuàng)建JSON對(duì)象,然后使用json_object_object_add函數(shù)將對(duì)象中的各個(gè)屬性添加到JSON中。最后,使用json_object_to_json_string將JSON對(duì)象轉(zhuǎn)換為JSON字符串。
使用時(shí),只需要將要轉(zhuǎn)換的C List作為參數(shù)傳入list_to_json_string函數(shù),即可獲得JSON格式的數(shù)據(jù)。