]>
git.proxmox.com Git - mirror_ovs.git/blob - tests/test-json.c
2 * Copyright (c) 2009 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(const char *input_file
)
72 struct json_parser
*parser
;
78 file
= fopen(input_file
, "r");
80 ovs_fatal(errno
, "Cannot open \"%s\"", input_file
);
86 while (used
< n
|| refill(file
, buffer
, sizeof buffer
, &n
, &used
)) {
87 if (!parser
&& isspace((unsigned char) buffer
[used
])) {
88 /* Skip white space. */
92 parser
= json_parser_create(0);
95 used
= n
- json_parser_feed(parser
, &buffer
[used
], n
- used
);
97 if (!print_and_free_json(json_parser_finish(parser
))) {
105 if (!print_and_free_json(json_parser_finish(parser
))) {
113 main(int argc
, char *argv
[])
115 const char *input_file
;
118 set_program_name(argv
[0]);
121 static const struct option options
[] = {
122 {"pretty", no_argument
, &pretty
, 1},
123 {"multiple", no_argument
, &multiple
, 1},
125 int option_index
= 0;
126 int c
= getopt_long (argc
, argv
, "", options
, &option_index
);
143 if (argc
- optind
!= 1) {
144 ovs_fatal(0, "usage: %s [--pretty] [--multiple] INPUT.json",
148 input_file
= argv
[optind
];
149 if (!strcmp(input_file
, "-")) {
150 input_file
= "/dev/stdin";
154 ok
= parse_multiple(input_file
);
156 ok
= print_and_free_json(json_from_file(input_file
));