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