2 * Copyright (C) 2013-2014 Jo-Philipp Wich <jo@mein.io>
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.
26 #include <json-c/json.h>
29 #include <libubox/list.h>
37 struct json_object *jsobj;
38 struct list_head list;
42 print_usage(char *app)
46 " # %s [-i <file> | -s \"json...\"] {-t <pattern> | -e <pattern>}\n"
47 " -q Quiet, no errors are printed\n"
48 " -h, --help Print this help\n"
49 " -i path Specify a JSON file to parse\n"
50 " -s \"json\" Specify a JSON string to parse\n"
51 " -l limit Specify max number of results to show\n"
52 " -F separator Specify a field separator when using export\n"
53 " -t <pattern> Print the type of values matched by pattern\n"
54 " -e <pattern> Print the values matched by pattern\n"
55 " -e VAR=<pat> Serialize matched value for shell \"eval\"\n\n"
57 " Patterns are JsonPath: http://goessner.net/articles/JsonPath/\n"
58 " This tool implements $, @, [], * and the union operator ','\n"
59 " plus the usual expressions and literals.\n"
60 " It does not support the recursive child search operator '..' or\n"
61 " the '?()' and '()' filter expressions as those would require a\n"
62 " complete JavaScript engine to support them.\n\n"
64 " Display the first IPv4 address on lan:\n"
65 " # ifstatus lan | %s -e '@[\"ipv4-address\"][0].address'\n\n"
66 " Extract the release string from the board information:\n"
67 " # ubus call system board | %s -e '@.release.description'\n\n"
68 " Find all interfaces which are up:\n"
69 " # ubus call network.interface dump | \\\n"
70 " %s -e '@.interface[@.up=true].interface'\n\n"
71 " Export br-lan traffic counters for shell eval:\n"
72 " # devstatus br-lan | %s -e 'RX=@.statistics.rx_bytes' \\\n"
73 " -e 'TX=@.statistics.tx_bytes'\n",
74 app, app, app, app, app);
77 static struct json_object *
78 parse_json(FILE *fd, const char *source, const char **error)
82 struct json_object *obj = NULL;
83 struct json_tokener *tok = json_tokener_new();
84 enum json_tokener_error err = json_tokener_continue;
91 obj = json_tokener_parse_ex(tok, source, strlen(source));
92 err = json_tokener_get_error(tok);
96 while ((len = fread(buf, 1, sizeof(buf), fd)) > 0)
98 obj = json_tokener_parse_ex(tok, buf, len);
99 err = json_tokener_get_error(tok);
101 if (!err || err != json_tokener_continue)
106 json_tokener_free(tok);
110 if (err == json_tokener_continue)
111 err = json_tokener_error_parse_eof;
113 *error = json_tokener_error_desc(err);
121 print_string(const char *s)
139 print_separator(const char *sep, int *sc, int sl)
143 switch (sep[(*sc - 1) % sl])
158 printf("%c", sep[(*sc - 1) % sl]);
166 export_value(struct list_head *matches, const char *prefix, const char *sep,
170 int sc = 0, sl = strlen(sep);
171 struct match_item *item;
173 if (list_empty(matches))
178 printf("export %s=", prefix);
180 list_for_each_entry(item, matches, list)
185 switch (json_object_get_type(item->jsobj))
187 case json_type_object:
188 ; /* a label can only be part of a statement */
189 json_object_object_foreach(item->jsobj, key, val)
194 print_separator(sep, &sc, sl);
199 case json_type_array:
200 for (n = 0, len = json_object_array_length(item->jsobj);
203 print_separator(sep, &sc, sl);
208 case json_type_boolean:
209 print_separator(sep, &sc, sl);
210 printf("%d", json_object_get_boolean(item->jsobj));
214 print_separator(sep, &sc, sl);
215 printf("%" PRId64, json_object_get_int64(item->jsobj));
218 case json_type_double:
219 print_separator(sep, &sc, sl);
220 printf("%f", json_object_get_double(item->jsobj));
223 case json_type_string:
224 print_separator(sep, &sc, sl);
225 print_string(json_object_get_string(item->jsobj));
237 list_for_each_entry(item, matches, list)
242 switch (json_object_get_type(item->jsobj))
244 case json_type_object:
245 case json_type_array:
246 case json_type_boolean:
248 case json_type_double:
249 printf("%s\n", json_object_to_json_string(item->jsobj));
252 case json_type_string:
253 printf("%s\n", json_object_get_string(item->jsobj));
264 export_type(struct list_head *matches, const char *prefix, int limit)
267 struct match_item *item;
268 const char *types[] = {
278 if (list_empty(matches))
282 printf("export %s=", prefix);
284 list_for_each_entry(item, matches, list)
292 printf("%s", types[json_object_get_type(item->jsobj)]);
303 match_cb(struct json_object *res, void *priv)
305 struct list_head *h = priv;
306 struct match_item *i = calloc(1, sizeof(*i));
311 list_add_tail(&i->list, h);
316 print_error(struct jp_state *state, char *expr)
321 fprintf(stderr, "Syntax error: ");
323 switch (state->error_code)
326 fprintf(stderr, "Unexpected character\n");
330 fprintf(stderr, "String or label literal too long\n");
334 fprintf(stderr, "Invalid escape sequence\n");
338 fprintf(stderr, "Unterminated string\n");
342 for (i = 0; i < sizeof(state->error_code) * 8; i++)
344 if (state->error_code & (1 << i))
347 first ? "Expecting %s" : " or %s", tokennames[i]);
353 fprintf(stderr, "\n");
357 fprintf(stderr, "In expression %s\n", expr);
358 fprintf(stderr, "Near here ----");
360 for (i = 0; i < state->error_pos; i++)
361 fprintf(stderr, "-");
363 fprintf(stderr, "^\n");
367 filter_json(int opt, struct json_object *jsobj, char *expr, const char *sep,
370 struct jp_state *state;
371 const char *prefix = NULL;
372 struct list_head matches;
373 struct match_item *item, *tmp;
374 struct json_object *res = NULL;
376 state = jp_parse(expr);
380 fprintf(stderr, "Out of memory\n");
383 else if (state->error_code)
385 print_error(state, expr);
389 INIT_LIST_HEAD(&matches);
391 res = jp_match(state->path, jsobj, match_cb, &matches);
392 prefix = (state->path->type == T_LABEL) ? state->path->str : NULL;
397 export_type(&matches, prefix, limit);
401 export_value(&matches, prefix, sep, limit);
405 list_for_each_entry_safe(item, tmp, &matches, list)
415 int main(int argc, char **argv)
417 int opt, rv = 0, limit = 0x7FFFFFFF;
419 struct json_object *jsobj = NULL;
420 const char *jserr = NULL, *source = NULL, *separator = " ";
424 print_usage(argv[0]);
428 while ((opt = getopt(argc, argv, "hi:s:e:t:F:l:q")) != -1)
433 print_usage(argv[0]);
437 input = fopen(optarg, "r");
441 fprintf(stderr, "Failed to open %s: %s\n",
442 optarg, strerror(errno));
455 if (optarg && *optarg)
460 limit = atoi(optarg);
467 jsobj = parse_json(input, source, &jserr);
471 fprintf(stderr, "Failed to parse json data: %s\n",
479 if (!filter_json(opt, jsobj, optarg, separator, limit))
492 json_object_put(jsobj);
494 if (input && input != stdin)