Print array of structs to JSON (or nested/twodimensional array)
Harvie opened this issue · 1 comments
Harvie commented
Hello,
i am trying to iterate over array of structs. There are 3 elements and i can iterate over it in for() { printf() }
loops, but i can't get json_printf_array()
to call custom struct handler for each element. Any ideas what is wrong with my code? Causes segfault.
int print_my_struct(struct json_out *out, va_list *ap) {
struct mgos_lib_info *p = va_arg(*ap, struct mgos_lib_info *);
return json_printf(out, "{name: %s, version: %s}", p->name, p->version);
}
int main(void) {
printf("------------------\n");
for(size_t i = 0; i < (sizeof(mgos_libs_info) / sizeof(struct mgos_lib_info))-1; i++) {
printf("FHS DETECTED MODULE: %s version %s (init:%d)\n",
mgos_libs_info[i].name,
mgos_libs_info[i].version,
mgos_libs_info[i].init
);
}
printf("------------------\n");
for (const struct mgos_lib_info *l = mgos_libs_info; l->name != NULL; l++) {
printf("FHS DETECTED MODULE: %s version %s\n", l->name, l->version);
}
printf("------------------\n");
char *json = json_asprintf("{modules:%M}",
json_printf_array, mgos_libs_info, 3 * sizeof(mgos_libs_info[0]),
sizeof(mgos_libs_info[0]), "%M", print_my_struct);
if (json) {
printf("%s\n", json);
free(json);
}
}
Harvie commented
Is there way to print two dimensional (nested) array? That would probably point me in the right direction...