2 * Copyright (C) 2013-2014 Jo-Philipp Wich <jow@openwrt.org>
4 * Permission to use, copy, modify, and/or distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
25 #include <json-c/json.h>
28 #include <libubox/list.h>
36 struct json_object *jsobj;
37 struct list_head list;
41 print_usage(char *app)
45 " # %s [-i <file> | -s \"json...\"] {-t <pattern> | -e <pattern>}\n"
46 " -q Quiet, no errors are printed\n"
47 " -h, --help Print this help\n"
48 " -i path Specify a JSON file to parse\n"
49 " -s \"json\" Specify a JSON string to parse\n"
50 " -l limit Specify max number of results to show\n"
51 " -F separator Specify a field separator when using export\n"
52 " -t <pattern> Print the type of values matched by pattern\n"
53 " -e <pattern> Print the values matched by pattern\n"
54 " -e VAR=<pat> Serialize matched value for shell \"eval\"\n\n"
56 " Patterns are JsonPath: http://goessner.net/articles/JsonPath/\n"
57 " This tool implements $, @, [], * and the union operator ','\n"
58 " plus the usual expressions and literals.\n"
59 " It does not support the recursive child search operator '..' or\n"
60 " the '?()' and '()' filter expressions as those would require a\n"
61 " complete JavaScript engine to support them.\n\n"
63 " Display the first IPv4 address on lan:\n"
64 " # ifstatus lan | %s -e '@[\"ipv4-address\"][0].address'\n\n"
65 " Extract the release string from the board information:\n"
66 " # ubus call system board | %s -e '@.release.description'\n\n"
67 " Find all interfaces which are up:\n"
68 " # ubus call network.interface dump | \\\n"
69 " %s -e '@.interface[@.up=true].interface'\n\n"
70 " Export br-lan traffic counters for shell eval:\n"
71 " # devstatus br-lan | %s -e 'RX=@.statistics.rx_bytes' \\\n"
72 " -e 'TX=@.statistics.tx_bytes'\n",
73 app, app, app, app, app);
76 static struct json_object *
77 parse_json(FILE *fd, const char *source, const char **error)
81 struct json_object *obj = NULL;
82 struct json_tokener *tok = json_tokener_new();
83 enum json_tokener_error err = json_tokener_continue;
90 obj = json_tokener_parse_ex(tok, source, strlen(source));
91 err = json_tokener_get_error(tok);
95 while ((len = fread(buf, 1, sizeof(buf), fd)) > 0)
97 obj = json_tokener_parse_ex(tok, buf, len);
98 err = json_tokener_get_error(tok);
100 if (!err || err != json_tokener_continue)
105 json_tokener_free(tok);
109 if (err == json_tokener_continue)
110 err = json_tokener_error_parse_eof;
112 *error = json_tokener_error_desc(err);
120 print_string(const char *s)
138 print_separator(const char *sep, int *sc, int sl)
142 switch (sep[(*sc - 1) % sl])
157 printf("%c", sep[(*sc - 1) % sl]);
165 export_value(struct list_head *matches, const char *prefix, const char *sep,
169 int sc = 0, sl = strlen(sep);
170 struct match_item *item;
172 if (list_empty(matches))
177 printf("export %s=", prefix);
179 list_for_each_entry(item, matches, list)
184 switch (json_object_get_type(item->jsobj))
186 case json_type_object:
187 ; /* a label can only be part of a statement */
188 json_object_object_foreach(item->jsobj, key, val)
193 print_separator(sep, &sc, sl);
198 case json_type_array:
199 for (n = 0, len = json_object_array_length(item->jsobj);
202 print_separator(sep, &sc, sl);
207 case json_type_boolean:
208 print_separator(sep, &sc, sl);
209 printf("%d", json_object_get_boolean(item->jsobj));
213 print_separator(sep, &sc, sl);
214 printf("%d", json_object_get_int(item->jsobj));
217 case json_type_double:
218 print_separator(sep, &sc, sl);
219 printf("%f", json_object_get_double(item->jsobj));
222 case json_type_string:
223 print_separator(sep, &sc, sl);
224 print_string(json_object_get_string(item->jsobj));
236 list_for_each_entry(item, matches, list)
241 switch (json_object_get_type(item->jsobj))
243 case json_type_object:
244 case json_type_array:
245 case json_type_boolean:
247 case json_type_double:
248 printf("%s\n", json_object_to_json_string(item->jsobj));
251 case json_type_string:
252 printf("%s\n", json_object_get_string(item->jsobj));
263 export_type(struct list_head *matches, const char *prefix, int limit)
266 struct match_item *item;
267 const char *types[] = {
277 if (list_empty(matches))
281 printf("export %s=", prefix);
283 list_for_each_entry(item, matches, list)
291 printf("%s", types[json_object_get_type(item->jsobj)]);
302 match_cb(struct json_object *res, void *priv)
304 struct list_head *h = priv;
305 struct match_item *i = calloc(1, sizeof(*i));
310 list_add_tail(&i->list, h);
315 print_error(struct jp_state *state, char *expr)
320 fprintf(stderr, "Syntax error: ");
322 switch (state->error_code)
325 fprintf(stderr, "Unexpected character\n");
329 fprintf(stderr, "String or label literal too long\n");
333 fprintf(stderr, "Invalid escape sequence\n");
337 fprintf(stderr, "Unterminated string\n");
341 for (i = 0; i < sizeof(state->error_code) * 8; i++)
343 if (state->error_code & (1 << i))
346 first ? "Expecting %s" : " or %s", tokennames[i]);
352 fprintf(stderr, "\n");
356 fprintf(stderr, "In expression %s\n", expr);
357 fprintf(stderr, "Near here ----");
359 for (i = 0; i < state->error_pos; i++)
360 fprintf(stderr, "-");
362 fprintf(stderr, "^\n");
366 filter_json(int opt, struct json_object *jsobj, char *expr, const char *sep,
369 struct jp_state *state;
370 const char *prefix = NULL;
371 struct list_head matches;
372 struct match_item *item, *tmp;
373 struct json_object *res = NULL;
375 state = jp_parse(expr);
379 fprintf(stderr, "Out of memory\n");
382 else if (state->error_code)
384 print_error(state, expr);
388 INIT_LIST_HEAD(&matches);
390 res = jp_match(state->path, jsobj, match_cb, &matches);
391 prefix = (state->path->type == T_LABEL) ? state->path->str : NULL;
396 export_type(&matches, prefix, limit);
400 export_value(&matches, prefix, sep, limit);
404 list_for_each_entry_safe(item, tmp, &matches, list)
414 int main(int argc, char **argv)
416 int opt, rv = 0, limit = 0x7FFFFFFF;
418 struct json_object *jsobj = NULL;
419 const char *jserr = NULL, *source = NULL, *separator = " ";
423 print_usage(argv[0]);
427 while ((opt = getopt(argc, argv, "hi:s:e:t:F:l:q")) != -1)
432 print_usage(argv[0]);
436 input = fopen(optarg, "r");
440 fprintf(stderr, "Failed to open %s: %s\n",
441 optarg, strerror(errno));
454 if (optarg && *optarg)
459 limit = atoi(optarg);
466 jsobj = parse_json(input, source, &jserr);
470 fprintf(stderr, "Failed to parse json data: %s\n",
478 if (!filter_json(opt, jsobj, optarg, separator, limit))
491 json_object_put(jsobj);
493 if (input && input != stdin)