Merge branch 'master' into yaz-744
[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
17 void usage(const char *prog)
18 {
19     fprintf(stderr, "%s: [-p]\n", prog);
20     exit(1);
21 }
22
23 static struct json_node *do_parse_from_stdin(void)
24 {
25     FILE *f = stdin;
26     WRBUF w = wrbuf_alloc();
27     struct json_node *n;
28     size_t pos;
29     const char *json_str;
30     const char *err_msg;
31     int c;
32
33     while ((c = getc(f)) != EOF)
34         wrbuf_putc(w, c);
35     json_str = wrbuf_cstr(w);
36     n = json_parse2(json_str, &err_msg, &pos);
37     if (!n)
38     {
39         fprintf(stderr, "JSON parse error: %s\nLeading text was:\n", err_msg);
40         fwrite(json_str, 1, pos, stderr);
41         fprintf(stderr, "^\n");
42     }
43     wrbuf_destroy(w);
44     return n;
45 }
46
47 int main(int argc, char **argv)
48 {
49     struct json_node *n;
50     int print = 0;
51     int ret;
52     char *arg;
53     while ((ret = options("p", argv, argc, &arg)) != YAZ_OPTIONS_EOF)
54     {
55         switch (ret)
56         {
57         case 'p':
58             print++;
59             break;
60         default:
61             usage(argv[0]);
62         }
63     }
64     n = do_parse_from_stdin();
65     if (!n)
66         exit(1);
67     if (print)
68     {
69         WRBUF result = wrbuf_alloc();
70         if (print > 1)
71             json_write_wrbuf_pretty(n, result);
72         else
73             json_write_wrbuf(n, result);
74         puts(wrbuf_cstr(result));
75         wrbuf_destroy(result);
76     }
77     json_remove_node(n);
78     return 0;
79 }
80 /*
81  * Local variables:
82  * c-basic-offset: 4
83  * c-file-style: "Stroustrup"
84  * indent-tabs-mode: nil
85  * End:
86  * vim: shiftwidth=4 tabstop=8 expandtab
87  */
88