2 * Copyright (c) 2009, 2010, 2014 Nicira, Inc.
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.
27 /* --pretty: If set, the JSON output is pretty-printed, instead of printed as
28 * compactly as possible. */
29 static int pretty = 0;
31 /* --multiple: If set, the input is a sequence of JSON objects or arrays,
32 * instead of exactly one object or array. */
33 static int multiple = 0;
36 print_and_free_json(struct json *json)
39 if (json->type == JSON_STRING) {
40 printf("error: %s\n", json->u.string);
43 char *s = json_to_string(json, JSSF_SORT | (pretty ? JSSF_PRETTY : 0));
53 refill(FILE *file, void *buffer, size_t buffer_size, size_t *n, size_t *used)
60 *n = fread(buffer, 1, buffer_size, file);
62 ovs_fatal(errno, "Error reading input file");
69 parse_multiple(FILE *stream)
71 struct json_parser *parser;
79 while (used < n || refill(stream, buffer, sizeof buffer, &n, &used)) {
80 if (!parser && isspace((unsigned char) buffer[used])) {
81 /* Skip white space. */
85 parser = json_parser_create(0);
88 used += json_parser_feed(parser, &buffer[used], n - used);
90 if (!print_and_free_json(json_parser_finish(parser))) {
98 if (!print_and_free_json(json_parser_finish(parser))) {
106 test_json_main(int argc, char *argv[])
108 const char *input_file;
112 set_program_name(argv[0]);
115 static const struct option options[] = {
116 {"pretty", no_argument, &pretty, 1},
117 {"multiple", no_argument, &multiple, 1},
119 int option_index = 0;
120 int c = getopt_long (argc, argv, "", options, &option_index);
137 if (argc - optind != 1) {
138 ovs_fatal(0, "usage: %s [--pretty] [--multiple] INPUT.json",
142 input_file = argv[optind];
143 stream = !strcmp(input_file, "-") ? stdin : fopen(input_file, "r");
145 ovs_fatal(errno, "Cannot open \"%s\"", input_file);
149 ok = parse_multiple(stream);
151 ok = print_and_free_json(json_from_stream(stream));
159 OVSTEST_REGISTER("test-json", test_json_main);