Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Print array of structs to JSON (or nested/twodimensional array) #58

Open
Harvie opened this issue Jun 1, 2020 · 1 comment
Open

Print array of structs to JSON (or nested/twodimensional array) #58

Harvie opened this issue Jun 1, 2020 · 1 comment

Comments

@Harvie
Copy link

Harvie commented Jun 1, 2020

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
Copy link
Author

Harvie commented Jun 1, 2020

Is there way to print two dimensional (nested) array? That would probably point me in the right direction...

@Harvie Harvie changed the title Print array of structs to JSON Print array of structs to JSON (or nested/twodimensional array) Jun 1, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant