]> mj.ucw.cz Git - libucw.git/blob - ucw-json/json-test.c
JSON: More parsing and formatting details
[libucw.git] / ucw-json / json-test.c
1 /*
2  *      UCW JSON Library -- Tests
3  *
4  *      (c) 2015 Martin Mares <mj@ucw.cz>
5  *
6  *      This software may be freely distributed and used according to the terms
7  *      of the GNU Lesser General Public License.
8  */
9
10 #include <ucw/lib.h>
11 #include <ucw/fastbuf.h>
12 #include <ucw/opt.h>
13 #include <ucw/trans.h>
14 #include <ucw-json/json.h>
15
16 static int opt_read;
17 static int opt_write;
18 static int opt_escape;
19 static int opt_indent;
20
21 static struct opt_section options = {
22   OPT_ITEMS {
23     OPT_HELP("Test program for UCW JSON library."),
24     OPT_HELP("Usage: json-test [options]"),
25     OPT_HELP(""),
26     OPT_HELP("Options:"),
27     OPT_HELP_OPTION,
28     OPT_BOOL('r', "read", opt_read, 0, "\tRead JSON from standard input"),
29     OPT_BOOL('w', "write", opt_write, 0, "\tWrite JSON to standard output"),
30     OPT_BOOL('e', "escape", opt_escape, 0, "\tEscape non-ASCII characters in strings"),
31     OPT_BOOL('i', "indent", opt_indent, 0, "\tIndent output"),
32     OPT_END
33   }
34 };
35
36 int main(int argc UNUSED, char **argv)
37 {
38   opt_parse(&options, argv+1);
39
40   struct json_context *js = json_new();
41   struct json_node *n = NULL;
42
43   if (opt_escape)
44     js->format_options |= JSON_FORMAT_ESCAPE_NONASCII;
45   if (opt_indent)
46     js->format_options |= JSON_FORMAT_INDENT;
47
48   if (opt_read)
49     {
50       struct fastbuf *fb = bfdopen_shared(0, 65536);
51       TRANS_TRY
52         {
53           n = json_parse(js, fb);
54         }
55       TRANS_CATCH(x)
56         {
57           fprintf(stderr, "ERROR: %s\n", x->msg);
58           exit(1);
59         }
60       TRANS_END;
61       bclose(fb);
62     }
63
64   if (!n)
65     {
66       n = json_new_number(js, 42);
67     }
68
69   if (opt_write)
70     {
71       struct fastbuf *fb = bfdopen_shared(1, 65536);
72       json_write(js, fb, n);
73       bclose(fb);
74     }
75
76   json_delete(js);
77   return 0;
78 }