/* main.c */ /* This program demonstrates a simple application of JSON_parser. It reads a JSON text from STDIN, producing an error message if the text is rejected. % JSON_parser #include #include #include #include #include "json.h" #include #include #include static int level = 0; static int got_key = 0; static void print_indent() { printf ("%*s", 2 * level, ""); } static bool array_begin (void *data) { if (!got_key) print_indent(); else got_key = 0; printf ("[\n"); ++level; return true; } static bool array_end (void *data) { --level; print_indent (); printf ("]\n"); return true; } static bool object_begin (void *data) { if (!got_key) print_indent(); else got_key = 0; printf ("{\n"); ++level; return true; } static bool object_end (void *data) { --level; print_indent (); printf ("}\n"); return true; } static bool key (void *data, const char *buf, size_t n) { got_key = 1; print_indent (); if (buf) printf ("key = '%s', value = ", buf); else printf ("user key = %%%c, value = ", getchar()); return true; } static bool value_integer (void *data, long long ll) { if (!got_key) print_indent(); else got_key = 0; printf ("integer: %lld\n", ll); return true; } static bool value_float (void *data, double d) { if (!got_key) print_indent(); else got_key = 0; printf ("float: %f\n", d); return true; } static bool value_null (void *data) { if (!got_key) print_indent(); else got_key = 0; printf ("null\n"); return true; } static bool value_boolean (void *data, int val) { if (!got_key) print_indent(); else got_key = 0; printf ("%s\n", val ? "true" : "false"); return true; } static bool value_string (void *data, const char *buf, size_t n) { if (!got_key) print_indent(); else got_key = 0; printf ("string: '%s'\n", buf); return true; } static bool value_user (void *data) { if (!got_key) print_indent(); else got_key = 0; printf ("user: %%%c\n", getchar()); return true; } int main(int argc, char* argv[]) { static struct json_parser_config parser_config = { .array_begin = array_begin, .array_end = array_end, .object_begin = object_begin, .object_end = object_end, .key = key, .value_integer = value_integer, .value_float = value_float, .value_null = value_null, .value_boolean = value_boolean, .value_string = value_string, .value_user = value_user, }; struct json_parser *p = json_parser_new(&parser_config); int count = 0; int ch; while ((ch = getchar ()) != EOF && json_parser_char (p, ch)) count++; if (ch != EOF) { fprintf (stderr, "error at character %d\n", count); exit (1); } if (!json_parser_destroy (p)) { fprintf (stderr, "error at end of file\n"); exit (1); } exit (0); }