C語(yǔ)言中的JSON解析庫(kù)提供了方便的方式,可以將JSON字符串解析成C中的數(shù)據(jù)類型。在解析JSON數(shù)據(jù)時(shí),我們可能會(huì)遇到將JSON數(shù)組轉(zhuǎn)換為JSON對(duì)象數(shù)組的情況。下面我們來(lái)看看如何實(shí)現(xiàn)這個(gè)轉(zhuǎn)換。
//下面是原始的JSON數(shù)組格式: { "students": [ { "name": "Tom", "age": 18, "gender": "male" }, { "name": "Kate", "age": 20, "gender": "female" } ] } //我們需要把它轉(zhuǎn)換為以下JSON對(duì)象數(shù)組格式: [ { "name": "Tom", "age": 18, "gender": "male" }, { "name": "Kate", "age": 20, "gender": "female" } ]
實(shí)現(xiàn)起來(lái)也很簡(jiǎn)單,就是遍歷原始JSON數(shù)組并將其中的每個(gè)JSON對(duì)象提取出來(lái)存儲(chǔ)到新的JSON對(duì)象數(shù)組中。
#include#include #include #include "cJSON.h" int main() { const char* json_str = "{ \"students\": [ { \"name\": \"Tom\", \"age\": 18, \"gender\": \"male\" }, { \"name\": \"Kate\", \"age\": 20, \"gender\": \"female\" } ] }"; //解析JSON字符串 cJSON* root = cJSON_Parse(json_str); if (!root) { printf("Error before: [%s]\n", cJSON_GetErrorPtr()); return -1; } //獲取JSON數(shù)組“students” cJSON* students = cJSON_GetObjectItem(root, "students"); if (!students) { cJSON_Delete(root); return -1; } //獲取JSON數(shù)組大小 int size = cJSON_GetArraySize(students); //遍歷數(shù)組,提取JSON對(duì)象 cJSON* student = NULL; cJSON* student_arr[size]; for (int i = 0; i< size; i++) { student = cJSON_GetArrayItem(students, i); if (student) { student_arr[i] = student; } } //將JSON對(duì)象數(shù)組轉(zhuǎn)換為JSON字符串 cJSON* new_root = cJSON_CreateArray(); if (!new_root) { cJSON_Delete(root); return -1; } for (int i = 0; i< size; i++) { if (student_arr[i]) { cJSON_AddItemToArray(new_root, student_arr[i]); } } char* new_json_str = cJSON_Print(new_root); //輸出結(jié)果 printf("new json string: %s\n", new_json_str); //釋放內(nèi)存 cJSON_Delete(root); cJSON_Delete(new_root); free(new_json_str); return 0; }
以上就是C語(yǔ)言中如何將JSON數(shù)組轉(zhuǎn)換為JSON對(duì)象數(shù)組的全部?jī)?nèi)容。掌握了這個(gè)重要的JSON解析技巧,我們可以更加靈活地處理JSON數(shù)據(jù),為軟件開發(fā)和大數(shù)據(jù)處理打下堅(jiān)實(shí)的基礎(chǔ)。