在C語言中,生成嵌套明細(xì)的JSON可以使用json-c庫。
首先,需要定義JSON對象的結(jié)構(gòu)。可以使用json_object_new_object()函數(shù)來創(chuàng)建一個JSON對象。然后,可以使用json_object_object_add()函數(shù)來添加鍵值對。如果值是一個對象或數(shù)組,則需要先創(chuàng)建一個新的對象或數(shù)組,然后將其添加為值。
下面是一個示例代碼:
#include#include int main() { struct json_object *obj, *arr, *inner_obj; // 創(chuàng)建對象 {"name": "Tom", "age": 18, "skills": [{"name": "coding", "level": 5}, {"name": "design", "level": 3}]} obj = json_object_new_object(); json_object_object_add(obj, "name", json_object_new_string("Tom")); json_object_object_add(obj, "age", json_object_new_int(18)); // 創(chuàng)建數(shù)組 [{"name": "coding", "level": 5}, {"name": "design", "level": 3}] arr = json_object_new_array(); inner_obj = json_object_new_object(); json_object_object_add(inner_obj, "name", json_object_new_string("coding")); json_object_object_add(inner_obj, "level", json_object_new_int(5)); json_object_array_add(arr, inner_obj); inner_obj = json_object_new_object(); json_object_object_add(inner_obj, "name", json_object_new_string("design")); json_object_object_add(inner_obj, "level", json_object_new_int(3)); json_object_array_add(arr, inner_obj); // 將數(shù)組添加到對象中 json_object_object_add(obj, "skills", arr); // 打印JSON printf("%s", json_object_to_json_string(obj)); return 0; }
輸出結(jié)果為:
{"name":"Tom","age":18,"skills":[{"name":"coding","level":5},{"name":"design","level":3}]}
可以看到,生成嵌套明細(xì)的JSON并不難,只需要按照一定的格式創(chuàng)建JSON對象和數(shù)組,然后添加鍵值對即可。