c语言用json格式用一个结构体写出三个数组并拼接输出结果
时间: 2023-04-03 14:02:35 浏览: 108
可以使用以下代码实现:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <json-c/json.h>
struct data {
int id;
char name[20];
float score;
};
int main() {
struct data arr1[3] = {{1, "Tom", 90.5}, {2, "Jerry", 80.}, {3, "Alice", 95.}};
struct data arr2[3] = {{4, "Bob", 85.}, {5, "Lucy", 92.5}, {6, "John", 88.}};
struct data arr3[3] = {{7, "Kate", 91.}, {8, "Mike", 87.5}, {9, "Mary", 89.}};
json_object *jobj = json_object_new_object();
json_object *jarr = json_object_new_array();
for (int i = ; i < 3; i++) {
json_object *jdata = json_object_new_object();
json_object_object_add(jdata, "id", json_object_new_int(arr1[i].id));
json_object_object_add(jdata, "name", json_object_new_string(arr1[i].name));
json_object_object_add(jdata, "score", json_object_new_double(arr1[i].score));
json_object_array_add(jarr, jdata);
}
for (int i = ; i < 3; i++) {
json_object *jdata = json_object_new_object();
json_object_object_add(jdata, "id", json_object_new_int(arr2[i].id));
json_object_object_add(jdata, "name", json_object_new_string(arr2[i].name));
json_object_object_add(jdata, "score", json_object_new_double(arr2[i].score));
json_object_array_add(jarr, jdata);
}
for (int i = ; i < 3; i++) {
json_object *jdata = json_object_new_object();
json_object_object_add(jdata, "id", json_object_new_int(arr3[i].id));
json_object_object_add(jdata, "name", json_object_new_string(arr3[i].name));
json_object_object_add(jdata, "score", json_object_new_double(arr3[i].score));
json_object_array_add(jarr, jdata);
}
json_object_object_add(jobj, "data", jarr);
const char *json_str = json_object_to_json_string(jobj);
printf("%s\n", json_str);
json_object_put(jobj);
return ;
}
阅读全文