db3e47314dbc6c258e45dc3f720c989ed535cd0c
[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     const char *json_str;
26     const char *err_msg;
27     int c;
28
29     while ((c = getc(f)) != EOF)
30         wrbuf_putc(w, c);
31     json_str = wrbuf_cstr(w);
32     n = json_parse(json_str, &err_msg);
33     if (!n)
34         fprintf(stderr, "JSON parse error: %s\n", err_msg);
35     wrbuf_destroy(w);
36     return n;
37 }
38
39 int main(int argc, char **argv)
40 {
41     struct json_node *n;
42     int print = 0;
43     int ret;
44     char *arg;
45     while ((ret = options("p", argv, argc, &arg)) != YAZ_OPTIONS_EOF)
46     {
47         switch (ret)
48         {
49         case 'p':
50             print = 1;
51             break;
52         default:
53             usage(argv[0]);
54         }
55     }
56     n = do_parse_from_stdin();
57     if (!n)
58         exit(1);
59     if (print)
60     {
61         WRBUF result = wrbuf_alloc();
62         json_write_wrbuf(n, result);
63         puts(wrbuf_cstr(result));
64         wrbuf_destroy(result);
65     }
66     json_remove_node(n);
67     return 0;
68 }
69 /*
70  * Local variables:
71  * c-basic-offset: 4
72  * c-file-style: "Stroustrup"
73  * indent-tabs-mode: nil
74  * End:
75  * vim: shiftwidth=4 tabstop=8 expandtab
76  */
77