dae869e5ec549ed3a1b618c421487b0e01bc1abf
[yaz-moved-to-github.git] / util / json-parse.c
1 /* This file is part of the YAZ toolkit.
2  * Copyright (C) 1995-2010 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 = 1;
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         json_write_wrbuf(n, result);
71         puts(wrbuf_cstr(result));
72         wrbuf_destroy(result);
73     }
74     json_remove_node(n);
75     return 0;
76 }
77 /*
78  * Local variables:
79  * c-basic-offset: 4
80  * c-file-style: "Stroustrup"
81  * indent-tabs-mode: nil
82  * End:
83  * vim: shiftwidth=4 tabstop=8 expandtab
84  */
85