在C語(yǔ)言中遍歷JSON對(duì)象集合可以使用第三方庫(kù),比如JSON-C庫(kù)。該庫(kù)提供了讀取和修改JSON對(duì)象的API。
// JSON-C使用示例 // 創(chuàng)建JSON對(duì)象 json_object *jobj = json_object_new_object(); // 添加字符串屬性 json_object_object_add(jobj, "description", json_object_new_string("JSON-C demo")); // 添加整數(shù)屬性 json_object_object_add(jobj, "version", json_object_new_int(1)); // 遍歷數(shù)組 json_object *jarray = json_object_new_array(); int i; for (i = 0; i< 3; i++) { json_object *jitem = json_object_new_string("item"); json_object_array_add(jarray, jitem); } json_object_object_add(jobj, "list", jarray); // 遍歷對(duì)象 json_object *jnested = json_object_new_object(); json_object_object_add(jnested, "key", json_object_new_string("value")); json_object_object_add(jobj, "nested", jnested); // 輸出JSON字符串 char *output = (char*)json_object_to_json_string(jobj); printf("output: %s\n", output);
JSON-C還提供了從文件讀取JSON對(duì)象或?qū)SON對(duì)象寫(xiě)入文件的函數(shù)。
// 從文件讀取JSON對(duì)象 char *filename = "input.json"; json_object *jinput = json_object_from_file(filename); // 判斷讀取是否成功 if (jinput == NULL) { printf("failed to read input file\n"); return; } // 修改JSON對(duì)象 json_object_object_add(jinput, "author", json_object_new_string("JSON-C team")); // 將JSON對(duì)象寫(xiě)入文件 char *output_filename = "output.json"; FILE *fp = fopen(output_filename, "w"); if (fp != NULL) { fputs(json_object_to_json_string(jinput), fp); } fclose(fp);
在讀取JSON對(duì)象時(shí),需要根據(jù)實(shí)際需要選擇從文件、字符串或流中讀取。在寫(xiě)入JSON對(duì)象時(shí),可以選擇按照格式化或緊湊的方式輸出。