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.
29 #include "dynamic-string.h"
35 /* The type of a JSON token. */
36 enum json_token_type {
42 T_NAME_SEPARATOR = ':',
43 T_VALUE_SEPARATOR = ',',
44 T_FALSE = UCHAR_MAX + 1,
54 * RFC 4627 doesn't define a lexical structure for JSON but I believe this to
55 * be compliant with the standard.
58 enum json_token_type type;
61 long long int integer;
67 JSON_LEX_START, /* Not inside a token. */
68 JSON_LEX_NUMBER, /* Reading a number. */
69 JSON_LEX_KEYWORD, /* Reading a keyword. */
70 JSON_LEX_STRING, /* Reading a quoted string. */
71 JSON_LEX_ESCAPE /* In a quoted string just after a "\". */
74 enum json_parse_state {
75 JSON_PARSE_START, /* Beginning of input. */
76 JSON_PARSE_END, /* End of input. */
79 JSON_PARSE_OBJECT_INIT, /* Expecting '}' or an object name. */
80 JSON_PARSE_OBJECT_NAME, /* Expecting an object name. */
81 JSON_PARSE_OBJECT_COLON, /* Expecting ':'. */
82 JSON_PARSE_OBJECT_VALUE, /* Expecting an object value. */
83 JSON_PARSE_OBJECT_NEXT, /* Expecting ',' or '}'. */
86 JSON_PARSE_ARRAY_INIT, /* Expecting ']' or a value. */
87 JSON_PARSE_ARRAY_VALUE, /* Expecting a value. */
88 JSON_PARSE_ARRAY_NEXT /* Expecting ',' or ']'. */
91 struct json_parser_node {
99 /* Lexical analysis. */
100 enum json_lex_state lex_state;
101 struct ds buffer; /* Buffer for accumulating token text. */
107 enum json_parse_state parse_state;
108 #define JSON_MAX_HEIGHT 1000
109 struct json_parser_node *stack;
110 size_t height, allocated_height;
115 char *error; /* Error message, if any, null if none yet. */
118 static struct json *json_create(enum json_type type);
119 static void json_parser_input(struct json_parser *, struct json_token *);
121 static void json_error(struct json_parser *p, const char *format, ...)
125 json_type_to_string(enum json_type type)
156 /* Functions for manipulating struct json. */
159 json_null_create(void)
161 return json_create(JSON_NULL);
165 json_boolean_create(bool b)
167 return json_create(b ? JSON_TRUE : JSON_FALSE);
171 json_string_create_nocopy(char *s)
173 struct json *json = json_create(JSON_STRING);
179 json_string_create(const char *s)
181 return json_string_create_nocopy(xstrdup(s));
185 json_array_create_empty(void)
187 struct json *json = json_create(JSON_ARRAY);
188 json->u.array.elems = NULL;
190 json->u.array.n_allocated = 0;
195 json_array_add(struct json *array_, struct json *element)
197 struct json_array *array = json_array(array_);
198 if (array->n >= array->n_allocated) {
199 array->elems = x2nrealloc(array->elems, &array->n_allocated,
200 sizeof *array->elems);
202 array->elems[array->n++] = element;
206 json_array_trim(struct json *array_)
208 struct json_array *array = json_array(array_);
209 if (array->n < array->n_allocated){
210 array->n_allocated = array->n;
211 array->elems = xrealloc(array->elems, array->n * sizeof *array->elems);
216 json_array_create(struct json **elements, size_t n)
218 struct json *json = json_create(JSON_ARRAY);
219 json->u.array.elems = elements;
221 json->u.array.n_allocated = n;
226 json_array_create_1(struct json *elem0)
228 struct json **elems = xmalloc(sizeof *elems);
230 return json_array_create(elems, 1);
234 json_array_create_2(struct json *elem0, struct json *elem1)
236 struct json **elems = xmalloc(2 * sizeof *elems);
239 return json_array_create(elems, 2);
243 json_array_create_3(struct json *elem0, struct json *elem1, struct json *elem2)
245 struct json **elems = xmalloc(3 * sizeof *elems);
249 return json_array_create(elems, 3);
253 json_object_create(void)
255 struct json *json = json_create(JSON_OBJECT);
256 json->u.object = xmalloc(sizeof *json->u.object);
257 shash_init(json->u.object);
262 json_integer_create(long long int integer)
264 struct json *json = json_create(JSON_INTEGER);
265 json->u.integer = integer;
270 json_real_create(double real)
272 struct json *json = json_create(JSON_REAL);
278 json_object_put(struct json *json, const char *name, struct json *value)
280 json_destroy(shash_replace(json->u.object, name, value));
284 json_object_put_string(struct json *json, const char *name, const char *value)
286 json_object_put(json, name, json_string_create(value));
290 json_string(const struct json *json)
292 assert(json->type == JSON_STRING);
293 return json->u.string;
297 json_array(const struct json *json)
299 assert(json->type == JSON_ARRAY);
300 return (struct json_array *) &json->u.array;
304 json_object(const struct json *json)
306 assert(json->type == JSON_OBJECT);
307 return (struct shash *) json->u.object;
311 json_boolean(const struct json *json)
313 assert(json->type == JSON_TRUE || json->type == JSON_FALSE);
314 return json->type == JSON_TRUE;
318 json_real(const struct json *json)
320 assert(json->type == JSON_REAL || json->type == JSON_INTEGER);
321 return json->type == JSON_REAL ? json->u.real : json->u.integer;
325 json_integer(const struct json *json)
327 assert(json->type == JSON_INTEGER);
328 return json->u.integer;
331 static void json_destroy_object(struct shash *object);
332 static void json_destroy_array(struct json_array *array);
334 /* Frees 'json' and everything it points to, recursively. */
336 json_destroy(struct json *json)
339 switch (json->type) {
341 json_destroy_object(json->u.object);
345 json_destroy_array(&json->u.array);
349 free(json->u.string);
367 json_destroy_object(struct shash *object)
369 struct shash_node *node, *next;
371 SHASH_FOR_EACH_SAFE (node, next, object) {
372 struct json *value = node->data;
375 shash_delete(object, node);
377 shash_destroy(object);
382 json_destroy_array(struct json_array *array)
386 for (i = 0; i < array->n; i++) {
387 json_destroy(array->elems[i]);
392 static struct json *json_clone_object(const struct shash *object);
393 static struct json *json_clone_array(const struct json_array *array);
395 /* Returns a deep copy of 'json'. */
397 json_clone(const struct json *json)
399 switch (json->type) {
401 return json_clone_object(json->u.object);
404 return json_clone_array(&json->u.array);
407 return json_string_create(json->u.string);
412 return json_create(json->type);
415 return json_integer_create(json->u.integer);
418 return json_real_create(json->u.real);
427 json_clone_object(const struct shash *object)
429 struct shash_node *node;
432 json = json_object_create();
433 SHASH_FOR_EACH (node, object) {
434 struct json *value = node->data;
435 json_object_put(json, node->name, json_clone(value));
441 json_clone_array(const struct json_array *array)
446 elems = xmalloc(array->n * sizeof *elems);
447 for (i = 0; i < array->n; i++) {
448 elems[i] = json_clone(array->elems[i]);
450 return json_array_create(elems, array->n);
454 json_hash_object(const struct shash *object, size_t basis)
456 const struct shash_node **nodes;
459 nodes = shash_sort(object);
460 n = shash_count(object);
461 for (i = 0; i < n; i++) {
462 const struct shash_node *node = nodes[i];
463 basis = hash_string(node->name, basis);
464 basis = json_hash(node->data, basis);
470 json_hash_array(const struct json_array *array, size_t basis)
474 basis = hash_int(array->n, basis);
475 for (i = 0; i < array->n; i++) {
476 basis = json_hash(array->elems[i], basis);
482 json_hash(const struct json *json, size_t basis)
484 switch (json->type) {
486 return json_hash_object(json->u.object, basis);
489 return json_hash_array(&json->u.array, basis);
492 return hash_string(json->u.string, basis);
497 return hash_int(json->type << 8, basis);
500 return hash_int(json->u.integer, basis);
503 return hash_double(json->u.real, basis);
512 json_equal_object(const struct shash *a, const struct shash *b)
514 struct shash_node *a_node;
516 if (shash_count(a) != shash_count(b)) {
520 SHASH_FOR_EACH (a_node, a) {
521 struct shash_node *b_node = shash_find(b, a_node->name);
522 if (!b_node || !json_equal(a_node->data, b_node->data)) {
531 json_equal_array(const struct json_array *a, const struct json_array *b)
539 for (i = 0; i < a->n; i++) {
540 if (!json_equal(a->elems[i], b->elems[i])) {
549 json_equal(const struct json *a, const struct json *b)
551 if (a->type != b->type) {
557 return json_equal_object(a->u.object, b->u.object);
560 return json_equal_array(&a->u.array, &b->u.array);
563 return !strcmp(a->u.string, b->u.string);
571 return a->u.integer == b->u.integer;
574 return a->u.real == b->u.real;
582 /* Lexical analysis. */
585 json_lex_keyword(struct json_parser *p)
587 struct json_token token;
590 s = ds_cstr(&p->buffer);
591 if (!strcmp(s, "false")) {
592 token.type = T_FALSE;
593 } else if (!strcmp(s, "true")) {
595 } else if (!strcmp(s, "null")) {
598 json_error(p, "invalid keyword '%s'", s);
601 json_parser_input(p, &token);
605 json_lex_number(struct json_parser *p)
607 const char *cp = ds_cstr(&p->buffer);
608 unsigned long long int significand = 0;
609 struct json_token token;
611 bool imprecise = false;
612 bool negative = false;
615 /* Leading minus sign. */
621 /* At least one integer digit, but 0 may not be used as a leading digit for
622 * a longer number. */
628 json_error(p, "leading zeros not allowed");
631 } else if (isdigit(*cp)) {
633 if (significand <= ULLONG_MAX / 10) {
634 significand = significand * 10 + (*cp - '0');
643 } while (isdigit(*cp));
645 json_error(p, "'-' must be followed by digit");
649 /* Optional fraction. */
653 json_error(p, "decimal point must be followed by digit");
657 if (significand <= ULLONG_MAX / 10) {
658 significand = significand * 10 + (*cp - '0');
661 } else if (*cp != '0') {
665 } while (isdigit(*cp));
668 /* Optional exponent. */
669 if (*cp == 'e' || *cp == 'E') {
670 bool negative_exponent = false;
676 } else if (*cp == '-') {
677 negative_exponent = true;
682 json_error(p, "exponent must contain at least one digit");
688 if (exponent >= INT_MAX / 10) {
689 json_error(p, "exponent outside valid range");
692 exponent = exponent * 10 + (*cp - '0');
694 } while (isdigit(*cp));
696 if (negative_exponent) {
704 json_error(p, "syntax error in number");
708 /* Figure out number.
710 * We suppress negative zeros as a matter of policy. */
712 struct json_token token;
713 token.type = T_INTEGER;
715 json_parser_input(p, &token);
720 while (pow10 > 0 && significand < ULLONG_MAX / 10) {
725 while (pow10 < 0 && significand % 10 == 0) {
731 && significand <= (negative
732 ? (unsigned long long int) LLONG_MAX + 1
734 token.type = T_INTEGER;
735 token.u.integer = negative ? -significand : significand;
736 json_parser_input(p, &token);
742 if (!str_to_double(ds_cstr(&p->buffer), &token.u.real)) {
743 json_error(p, "number outside valid range");
746 /* Suppress negative zero. */
747 if (token.u.real == 0) {
750 json_parser_input(p, &token);
754 json_lex_4hex(const char *cp, const char *end, int *valuep)
759 return "quoted string ends within \\u escape";
763 for (i = 0; i < 4; i++) {
764 unsigned char c = *cp++;
766 return "malformed \\u escape";
768 value = (value << 4) | hexit_value(c);
771 return "null bytes not supported in quoted strings";
778 json_lex_unicode(const char *cp, const char *end, struct ds *out)
783 error = json_lex_4hex(cp, end, &c0);
786 ds_put_cstr(out, error);
790 if (!uc_is_leading_surrogate(c0)) {
791 ds_put_utf8(out, c0);
795 if (cp + 2 > end || *cp++ != '\\' || *cp++ != 'u') {
797 ds_put_cstr(out, "malformed escaped surrogate pair");
801 error = json_lex_4hex(cp, end, &c1);
804 ds_put_cstr(out, error);
808 if (!uc_is_trailing_surrogate(c1)) {
810 ds_put_cstr(out, "second half of escaped surrogate pair is not "
811 "trailing surrogate");
815 ds_put_utf8(out, utf16_decode_surrogate_pair(c0, c1));
820 json_string_unescape(const char *in, size_t in_len, char **outp)
822 const char *end = in + in_len;
827 ds_reserve(&out, in_len);
828 if (in_len > 0 && in[in_len - 1] == '\\') {
829 ds_put_cstr(&out, "quoted string may not end with backslash");
835 ds_put_cstr(&out, "quoted string may not include unescaped \"");
839 ds_put_char(&out, *in++);
845 case '"': case '\\': case '/':
846 ds_put_char(&out, in[-1]);
850 ds_put_char(&out, '\b');
854 ds_put_char(&out, '\f');
858 ds_put_char(&out, '\n');
862 ds_put_char(&out, '\r');
866 ds_put_char(&out, '\t');
870 in = json_lex_unicode(in, end, &out);
878 ds_put_format(&out, "bad escape \\%c", in[-1]);
885 *outp = ds_cstr(&out);
890 json_parser_input_string(struct json_parser *p, const char *s)
892 struct json_token token;
894 token.type = T_STRING;
896 json_parser_input(p, &token);
900 json_lex_string(struct json_parser *p)
902 const char *raw = ds_cstr(&p->buffer);
903 if (!strchr(raw, '\\')) {
904 json_parser_input_string(p, raw);
908 if (json_string_unescape(raw, strlen(raw), &cooked)) {
909 json_parser_input_string(p, cooked);
911 json_error(p, "%s", cooked);
919 json_lex_input(struct json_parser *p, unsigned char c)
921 struct json_token token;
925 p->column_number = 0;
931 switch (p->lex_state) {
934 case ' ': case '\t': case '\n': case '\r':
938 case 'a': case 'b': case 'c': case 'd': case 'e':
939 case 'f': case 'g': case 'h': case 'i': case 'j':
940 case 'k': case 'l': case 'm': case 'n': case 'o':
941 case 'p': case 'q': case 'r': case 's': case 't':
942 case 'u': case 'v': case 'w': case 'x': case 'y':
944 p->lex_state = JSON_LEX_KEYWORD;
947 case '[': case '{': case ']': case '}': case ':': case ',':
949 json_parser_input(p, &token);
953 case '0': case '1': case '2': case '3': case '4':
954 case '5': case '6': case '7': case '8': case '9':
955 p->lex_state = JSON_LEX_NUMBER;
959 p->lex_state = JSON_LEX_STRING;
964 json_error(p, "invalid character '%c'", c);
966 json_error(p, "invalid character U+%04x", c);
972 case JSON_LEX_KEYWORD:
973 if (!isalpha((unsigned char) c)) {
979 case JSON_LEX_NUMBER:
980 if (!strchr(".0123456789eE-+", c)) {
986 case JSON_LEX_STRING:
988 p->lex_state = JSON_LEX_ESCAPE;
989 } else if (c == '"') {
992 } else if (c < 0x20) {
993 json_error(p, "U+%04X must be escaped in quoted string", c);
998 case JSON_LEX_ESCAPE:
999 p->lex_state = JSON_LEX_STRING;
1005 ds_put_char(&p->buffer, c);
1011 /* Parses 'string' as a JSON object or array and returns a newly allocated
1012 * 'struct json'. The caller must free the returned structure with
1013 * json_destroy() when it is no longer needed.
1015 * 'string' must be encoded in UTF-8.
1017 * If 'string' is valid JSON, then the returned 'struct json' will be either an
1018 * object (JSON_OBJECT) or an array (JSON_ARRAY).
1020 * If 'string' is not valid JSON, then the returned 'struct json' will be a
1021 * string (JSON_STRING) that describes the particular error encountered during
1022 * parsing. (This is an acceptable means of error reporting because at its top
1023 * level JSON must be either an object or an array; a bare string is not
1026 json_from_string(const char *string)
1028 struct json_parser *p = json_parser_create(JSPF_TRAILER);
1029 json_parser_feed(p, string, strlen(string));
1030 return json_parser_finish(p);
1033 /* Reads the file named 'file_name', parses its contents as a JSON object or
1034 * array, and returns a newly allocated 'struct json'. The caller must free
1035 * the returned structure with json_destroy() when it is no longer needed.
1037 * The file must be encoded in UTF-8.
1039 * See json_from_string() for return value semantics.
1042 json_from_file(const char *file_name)
1047 stream = fopen(file_name, "r");
1049 return json_string_create_nocopy(
1050 xasprintf("error opening \"%s\": %s", file_name, strerror(errno)));
1052 json = json_from_stream(stream);
1058 /* Parses the contents of 'stream' as a JSON object or array, and returns a
1059 * newly allocated 'struct json'. The caller must free the returned structure
1060 * with json_destroy() when it is no longer needed.
1062 * The file must be encoded in UTF-8.
1064 * See json_from_string() for return value semantics.
1067 json_from_stream(FILE *stream)
1069 struct json_parser *p;
1072 p = json_parser_create(JSPF_TRAILER);
1074 char buffer[BUFSIZ];
1077 n = fread(buffer, 1, sizeof buffer, stream);
1078 if (!n || json_parser_feed(p, buffer, n) != n) {
1082 json = json_parser_finish(p);
1084 if (ferror(stream)) {
1086 json = json_string_create_nocopy(
1087 xasprintf("error reading JSON stream: %s", strerror(errno)));
1093 struct json_parser *
1094 json_parser_create(int flags)
1096 struct json_parser *p = xzalloc(sizeof *p);
1102 json_parser_feed(struct json_parser *p, const char *input, size_t n)
1105 for (i = 0; !p->done && i < n; ) {
1106 if (json_lex_input(p, input[i])) {
1114 json_parser_is_done(const struct json_parser *p)
1120 json_parser_finish(struct json_parser *p)
1124 switch (p->lex_state) {
1125 case JSON_LEX_START:
1128 case JSON_LEX_STRING:
1129 case JSON_LEX_ESCAPE:
1130 json_error(p, "unexpected end of input in quoted string");
1133 case JSON_LEX_NUMBER:
1134 case JSON_LEX_KEYWORD:
1135 json_lex_input(p, ' ');
1139 if (p->parse_state == JSON_PARSE_START) {
1140 json_error(p, "empty input stream");
1141 } else if (p->parse_state != JSON_PARSE_END) {
1142 json_error(p, "unexpected end of input");
1146 assert(p->height == 1);
1147 assert(p->stack[0].json != NULL);
1148 json = p->stack[--p->height].json;
1150 json = json_string_create_nocopy(p->error);
1154 json_parser_abort(p);
1160 json_parser_abort(struct json_parser *p)
1163 ds_destroy(&p->buffer);
1165 json_destroy(p->stack[0].json);
1168 free(p->member_name);
1174 static struct json_parser_node *
1175 json_parser_top(struct json_parser *p)
1177 return &p->stack[p->height - 1];
1181 json_parser_put_value(struct json_parser *p, struct json *value)
1183 struct json_parser_node *node = json_parser_top(p);
1184 if (node->json->type == JSON_OBJECT) {
1185 json_object_put(node->json, p->member_name, value);
1186 free(p->member_name);
1187 p->member_name = NULL;
1188 } else if (node->json->type == JSON_ARRAY) {
1189 json_array_add(node->json, value);
1195 static struct json_parser_node *
1196 json_parser_push(struct json_parser *p,
1197 struct json *new_json, enum json_parse_state new_state)
1199 if (p->height < JSON_MAX_HEIGHT) {
1200 struct json_parser_node *node;
1202 if (p->height >= p->allocated_height) {
1203 p->stack = x2nrealloc(p->stack, &p->allocated_height,
1207 if (p->height > 0) {
1208 json_parser_put_value(p, new_json);
1211 node = &p->stack[p->height++];
1212 node->json = new_json;
1213 p->parse_state = new_state;
1216 json_destroy(new_json);
1217 json_error(p, "input exceeds maximum nesting depth %d",
1224 json_parser_push_object(struct json_parser *p)
1226 json_parser_push(p, json_object_create(), JSON_PARSE_OBJECT_INIT);
1230 json_parser_push_array(struct json_parser *p)
1232 json_parser_push(p, json_array_create_empty(), JSON_PARSE_ARRAY_INIT);
1236 json_parse_value(struct json_parser *p, struct json_token *token,
1237 enum json_parse_state next_state)
1241 switch (token->type) {
1243 value = json_boolean_create(false);
1247 value = json_null_create();
1251 value = json_boolean_create(true);
1255 json_parser_push_object(p);
1259 json_parser_push_array(p);
1263 value = json_integer_create(token->u.integer);
1267 value = json_real_create(token->u.real);
1271 value = json_string_create(token->u.string);
1280 json_error(p, "syntax error expecting value");
1284 json_parser_put_value(p, value);
1285 p->parse_state = next_state;
1289 json_parser_pop(struct json_parser *p)
1291 struct json_parser_node *node;
1293 /* Conserve memory. */
1294 node = json_parser_top(p);
1295 if (node->json->type == JSON_ARRAY) {
1296 json_array_trim(node->json);
1299 /* Pop off the top-of-stack. */
1300 if (p->height == 1) {
1301 p->parse_state = JSON_PARSE_END;
1302 if (!(p->flags & JSPF_TRAILER)) {
1307 node = json_parser_top(p);
1308 if (node->json->type == JSON_ARRAY) {
1309 p->parse_state = JSON_PARSE_ARRAY_NEXT;
1310 } else if (node->json->type == JSON_OBJECT) {
1311 p->parse_state = JSON_PARSE_OBJECT_NEXT;
1319 json_parser_input(struct json_parser *p, struct json_token *token)
1321 switch (p->parse_state) {
1322 case JSON_PARSE_START:
1323 if (token->type == '{') {
1324 json_parser_push_object(p);
1325 } else if (token->type == '[') {
1326 json_parser_push_array(p);
1328 json_error(p, "syntax error at beginning of input");
1332 case JSON_PARSE_END:
1333 json_error(p, "trailing garbage at end of input");
1336 case JSON_PARSE_OBJECT_INIT:
1337 if (token->type == '}') {
1342 case JSON_PARSE_OBJECT_NAME:
1343 if (token->type == T_STRING) {
1344 p->member_name = xstrdup(token->u.string);
1345 p->parse_state = JSON_PARSE_OBJECT_COLON;
1347 json_error(p, "syntax error parsing object expecting string");
1351 case JSON_PARSE_OBJECT_COLON:
1352 if (token->type == ':') {
1353 p->parse_state = JSON_PARSE_OBJECT_VALUE;
1355 json_error(p, "syntax error parsing object expecting ':'");
1359 case JSON_PARSE_OBJECT_VALUE:
1360 json_parse_value(p, token, JSON_PARSE_OBJECT_NEXT);
1363 case JSON_PARSE_OBJECT_NEXT:
1364 if (token->type == ',') {
1365 p->parse_state = JSON_PARSE_OBJECT_NAME;
1366 } else if (token->type == '}') {
1369 json_error(p, "syntax error expecting '}' or ','");
1373 case JSON_PARSE_ARRAY_INIT:
1374 if (token->type == ']') {
1379 case JSON_PARSE_ARRAY_VALUE:
1380 json_parse_value(p, token, JSON_PARSE_ARRAY_NEXT);
1383 case JSON_PARSE_ARRAY_NEXT:
1384 if (token->type == ',') {
1385 p->parse_state = JSON_PARSE_ARRAY_VALUE;
1386 } else if (token->type == ']') {
1389 json_error(p, "syntax error expecting ']' or ','");
1397 p->lex_state = JSON_LEX_START;
1398 ds_clear(&p->buffer);
1401 static struct json *
1402 json_create(enum json_type type)
1404 struct json *json = xmalloc(sizeof *json);
1410 json_error(struct json_parser *p, const char *format, ...)
1417 ds_put_format(&msg, "line %d, column %d, byte %d: ",
1418 p->line_number, p->column_number, p->byte_number);
1419 va_start(args, format);
1420 ds_put_format_valist(&msg, format, args);
1423 p->error = ds_steal_cstr(&msg);
1429 #define SPACES_PER_LEVEL 2
1431 struct json_serializer {
1437 static void json_serialize(const struct json *, struct json_serializer *);
1438 static void json_serialize_object(const struct shash *object,
1439 struct json_serializer *);
1440 static void json_serialize_array(const struct json_array *,
1441 struct json_serializer *);
1442 static void json_serialize_string(const char *, struct ds *);
1444 /* Converts 'json' to a string in JSON format, encoded in UTF-8, and returns
1445 * that string. The caller is responsible for freeing the returned string,
1446 * with free(), when it is no longer needed.
1448 * If 'flags' contains JSSF_PRETTY, the output is pretty-printed with each
1449 * nesting level introducing an additional indentation. Otherwise, the
1450 * returned string does not contain any new-line characters.
1452 * If 'flags' contains JSSF_SORT, members of objects in the output are sorted
1453 * in bytewise lexicographic order for reproducibility. Otherwise, members of
1454 * objects are output in an indeterminate order.
1456 * The returned string is valid JSON only if 'json' represents an array or an
1457 * object, since a bare literal does not satisfy the JSON grammar. */
1459 json_to_string(const struct json *json, int flags)
1464 json_to_ds(json, flags, &ds);
1465 return ds_steal_cstr(&ds);
1468 /* Same as json_to_string(), but the output is appended to 'ds'. */
1470 json_to_ds(const struct json *json, int flags, struct ds *ds)
1472 struct json_serializer s;
1477 json_serialize(json, &s);
1481 json_serialize(const struct json *json, struct json_serializer *s)
1483 struct ds *ds = s->ds;
1485 switch (json->type) {
1487 ds_put_cstr(ds, "null");
1491 ds_put_cstr(ds, "false");
1495 ds_put_cstr(ds, "true");
1499 json_serialize_object(json->u.object, s);
1503 json_serialize_array(&json->u.array, s);
1507 ds_put_format(ds, "%lld", json->u.integer);
1511 ds_put_format(ds, "%.*g", DBL_DIG, json->u.real);
1515 json_serialize_string(json->u.string, ds);
1525 indent_line(struct json_serializer *s)
1527 if (s->flags & JSSF_PRETTY) {
1528 ds_put_char(s->ds, '\n');
1529 ds_put_char_multiple(s->ds, ' ', SPACES_PER_LEVEL * s->depth);
1534 json_serialize_object_member(size_t i, const struct shash_node *node,
1535 struct json_serializer *s)
1537 struct ds *ds = s->ds;
1540 ds_put_char(ds, ',');
1544 json_serialize_string(node->name, ds);
1545 ds_put_char(ds, ':');
1546 if (s->flags & JSSF_PRETTY) {
1547 ds_put_char(ds, ' ');
1549 json_serialize(node->data, s);
1553 json_serialize_object(const struct shash *object, struct json_serializer *s)
1555 struct ds *ds = s->ds;
1557 ds_put_char(ds, '{');
1562 if (s->flags & JSSF_SORT) {
1563 const struct shash_node **nodes;
1566 nodes = shash_sort(object);
1567 n = shash_count(object);
1568 for (i = 0; i < n; i++) {
1569 json_serialize_object_member(i, nodes[i], s);
1573 struct shash_node *node;
1577 SHASH_FOR_EACH (node, object) {
1578 json_serialize_object_member(i++, node, s);
1582 ds_put_char(ds, '}');
1587 json_serialize_array(const struct json_array *array, struct json_serializer *s)
1589 struct ds *ds = s->ds;
1592 ds_put_char(ds, '[');
1598 for (i = 0; i < array->n; i++) {
1600 ds_put_char(ds, ',');
1603 json_serialize(array->elems[i], s);
1608 ds_put_char(ds, ']');
1612 json_serialize_string(const char *string, struct ds *ds)
1616 ds_put_char(ds, '"');
1617 while ((c = *string++) != '\0') {
1620 ds_put_cstr(ds, "\\\"");
1624 ds_put_cstr(ds, "\\\\");
1628 ds_put_cstr(ds, "\\b");
1632 ds_put_cstr(ds, "\\f");
1636 ds_put_cstr(ds, "\\n");
1640 ds_put_cstr(ds, "\\r");
1644 ds_put_cstr(ds, "\\t");
1651 ds_put_format(ds, "\\u%04x", c);
1656 ds_put_char(ds, '"');