2 * Copyright (c) 2009, 2010 Nicira Networks.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at:
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
28 /* --pretty: If set, the JSON output is pretty-printed, instead of printed as
29 * compactly as possible. */
30 static int pretty = 0;
32 /* --multiple: If set, the input is a sequence of JSON objects or arrays,
33 * instead of exactly one object or array. */
34 static int multiple = 0;
37 print_and_free_json(struct json *json)
40 if (json->type == JSON_STRING) {
41 printf("error: %s\n", json->u.string);
44 char *s = json_to_string(json, JSSF_SORT | (pretty ? JSSF_PRETTY : 0));
54 refill(FILE *file, void *buffer, size_t buffer_size, size_t *n, size_t *used)
61 *n = fread(buffer, 1, buffer_size, file);
63 ovs_fatal(errno, "Error reading input file");
70 parse_multiple(FILE *stream)
72 struct json_parser *parser;
80 while (used < n || refill(stream, buffer, sizeof buffer, &n, &used)) {
81 if (!parser && isspace((unsigned char) buffer[used])) {
82 /* Skip white space. */
86 parser = json_parser_create(0);
89 used += json_parser_feed(parser, &buffer[used], n - used);
91 if (!print_and_free_json(json_parser_finish(parser))) {
99 if (!print_and_free_json(json_parser_finish(parser))) {
107 main(int argc, char *argv[])
109 const char *input_file;
113 set_program_name(argv[0]);
116 static const struct option options[] = {
117 {"pretty", no_argument, &pretty, 1},
118 {"multiple", no_argument, &multiple, 1},
120 int option_index = 0;
121 int c = getopt_long (argc, argv, "", options, &option_index);
138 if (argc - optind != 1) {
139 ovs_fatal(0, "usage: %s [--pretty] [--multiple] INPUT.json",
143 input_file = argv[optind];
144 stream = !strcmp(input_file, "-") ? stdin : fopen(input_file, "r");
146 ovs_fatal(errno, "Cannot open \"%s\"", input_file);
150 ok = parse_multiple(stream);
152 ok = print_and_free_json(json_from_stream(stream));