CCL: split-list deals with use attr YAZ-844
[yaz-moved-to-github.git] / util / json-parse.c
1 /* This file is part of the YAZ toolkit.
2  * Copyright (C) Index Data
3  * See the file LICENSE for details.
4  */
5 #if HAVE_CONFIG_H
6 #include <config.h>
7 #endif
8
9 #include <stdio.h>
10 #include <stdlib.h>
11 #include <string.h>
12
13 #include <yaz/json.h>
14 #include <yaz/wrbuf.h>
15 #include <yaz/options.h>
16 #include <yaz/backtrace.h>
17
18 void usage(const char *prog)
19 {
20     fprintf(stderr, "%s: [-p]\n", prog);
21     exit(1);
22 }
23
24 static struct json_node *do_parse_from_stdin(void)
25 {
26     FILE *f = stdin;
27     WRBUF w = wrbuf_alloc();
28     struct json_node *n;
29     size_t pos;
30     const char *json_str;
31     const char *err_msg;
32     int c;
33
34     while ((c = getc(f)) != EOF)
35         wrbuf_putc(w, c);
36     json_str = wrbuf_cstr(w);
37     n = json_parse2(json_str, &err_msg, &pos);
38     if (!n)
39     {
40         fprintf(stderr, "JSON parse error: %s\nLeading text was:\n", err_msg);
41         fwrite(json_str, 1, pos, stderr);
42         fprintf(stderr, "^\n");
43     }
44     wrbuf_destroy(w);
45     return n;
46 }
47
48 int main(int argc, char **argv)
49 {
50     struct json_node *n;
51     int print = 0;
52     int ret;
53     char *arg;
54
55     yaz_enable_panic_backtrace(*argv);
56     while ((ret = options("p", argv, argc, &arg)) != YAZ_OPTIONS_EOF)
57     {
58         switch (ret)
59         {
60         case 'p':
61             print++;
62             break;
63         default:
64             usage(argv[0]);
65         }
66     }
67     n = do_parse_from_stdin();
68     if (!n)
69         exit(1);
70     if (print)
71     {
72         WRBUF result = wrbuf_alloc();
73         if (print > 1)
74             json_write_wrbuf_pretty(n, result);
75         else
76             json_write_wrbuf(n, result);
77         puts(wrbuf_cstr(result));
78         wrbuf_destroy(result);
79     }
80     json_remove_node(n);
81     return 0;
82 }
83 /*
84  * Local variables:
85  * c-basic-offset: 4
86  * c-file-style: "Stroustrup"
87  * indent-tabs-mode: nil
88  * End:
89  * vim: shiftwidth=4 tabstop=8 expandtab
90  */
91