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.
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_2(struct json *elem0, struct json *elem1)
228 struct json **elems = xmalloc(2 * sizeof *elems);
231 return json_array_create(elems, 2);
235 json_array_create_3(struct json *elem0, struct json *elem1, struct json *elem2)
237 struct json **elems = xmalloc(3 * sizeof *elems);
241 return json_array_create(elems, 3);
245 json_object_create(void)
247 struct json *json = json_create(JSON_OBJECT);
248 json->u.object = xmalloc(sizeof *json->u.object);
249 shash_init(json->u.object);
254 json_integer_create(long long int integer)
256 struct json *json = json_create(JSON_INTEGER);
257 json->u.integer = integer;
262 json_real_create(double real)
264 struct json *json = json_create(JSON_REAL);
270 json_object_put(struct json *json, const char *name, struct json *value)
272 shash_add(json->u.object, name, value);
276 json_object_put_string(struct json *json, const char *name, const char *value)
278 json_object_put(json, name, json_string_create(value));
282 json_string(const struct json *json)
284 assert(json->type == JSON_STRING);
285 return json->u.string;
289 json_array(const struct json *json)
291 assert(json->type == JSON_ARRAY);
292 return (struct json_array *) &json->u.array;
296 json_object(const struct json *json)
298 assert(json->type == JSON_OBJECT);
299 return (struct shash *) json->u.object;
303 json_boolean(const struct json *json)
305 assert(json->type == JSON_TRUE || json->type == JSON_FALSE);
306 return json->type == JSON_TRUE;
310 json_real(const struct json *json)
312 assert(json->type == JSON_REAL || json->type == JSON_INTEGER);
313 return json->type == JSON_REAL ? json->u.real : json->u.integer;
317 json_integer(const struct json *json)
319 assert(json->type == JSON_INTEGER);
320 return json->u.integer;
323 static void json_destroy_object(struct shash *object);
324 static void json_destroy_array(struct json_array *array);
326 /* Frees 'json' and everything it points to, recursively. */
328 json_destroy(struct json *json)
331 switch (json->type) {
333 json_destroy_object(json->u.object);
337 json_destroy_array(&json->u.array);
341 free(json->u.string);
359 json_destroy_object(struct shash *object)
361 struct shash_node *node, *next;
363 SHASH_FOR_EACH_SAFE (node, next, object) {
364 struct json *value = node->data;
367 shash_delete(object, node);
369 shash_destroy(object);
374 json_destroy_array(struct json_array *array)
378 for (i = 0; i < array->n; i++) {
379 json_destroy(array->elems[i]);
384 static struct json *json_clone_object(const struct shash *object);
385 static struct json *json_clone_array(const struct json_array *array);
387 /* Returns a deep copy of 'json'. */
389 json_clone(const struct json *json)
391 switch (json->type) {
393 return json_clone_object(json->u.object);
396 return json_clone_array(&json->u.array);
399 return json_string_create(json->u.string);
404 return json_create(json->type);
407 return json_integer_create(json->u.integer);
410 return json_real_create(json->u.real);
419 json_clone_object(const struct shash *object)
421 struct shash_node *node;
424 json = json_object_create();
425 SHASH_FOR_EACH (node, object) {
426 struct json *value = node->data;
427 json_object_put(json, node->name, json_clone(value));
433 json_clone_array(const struct json_array *array)
438 elems = xmalloc(array->n * sizeof *elems);
439 for (i = 0; i < array->n; i++) {
440 elems[i] = json_clone(array->elems[i]);
442 return json_array_create(elems, array->n);
446 json_hash_object(const struct shash *object, size_t basis)
448 const struct shash_node **nodes;
451 nodes = shash_sort(object);
452 n = shash_count(object);
453 for (i = 0; i < n; i++) {
454 const struct shash_node *node = nodes[i];
455 basis = hash_string(node->name, basis);
456 basis = json_hash(node->data, basis);
462 json_hash_array(const struct json_array *array, size_t basis)
466 basis = hash_int(array->n, basis);
467 for (i = 0; i < array->n; i++) {
468 basis = json_hash(array->elems[i], basis);
474 json_hash(const struct json *json, size_t basis)
476 switch (json->type) {
478 return json_hash_object(json->u.object, basis);
481 return json_hash_array(&json->u.array, basis);
484 return hash_string(json->u.string, basis);
489 return hash_int(json->type << 8, basis);
492 return hash_int(json->u.integer, basis);
495 return hash_double(json->u.real, basis);
504 json_equal_object(const struct shash *a, const struct shash *b)
506 struct shash_node *a_node;
508 if (shash_count(a) != shash_count(b)) {
512 SHASH_FOR_EACH (a_node, a) {
513 struct shash_node *b_node = shash_find(b, a_node->name);
514 if (!b_node || !json_equal(a_node->data, b_node->data)) {
523 json_equal_array(const struct json_array *a, const struct json_array *b)
531 for (i = 0; i < a->n; i++) {
532 if (!json_equal(a->elems[i], b->elems[i])) {
541 json_equal(const struct json *a, const struct json *b)
543 if (a->type != b->type) {
549 return json_equal_object(a->u.object, b->u.object);
552 return json_equal_array(&a->u.array, &b->u.array);
555 return !strcmp(a->u.string, b->u.string);
563 return a->u.integer == b->u.integer;
566 return a->u.real == b->u.real;
574 /* Lexical analysis. */
577 json_lex_keyword(struct json_parser *p)
579 struct json_token token;
582 s = ds_cstr(&p->buffer);
583 if (!strcmp(s, "false")) {
584 token.type = T_FALSE;
585 } else if (!strcmp(s, "true")) {
587 } else if (!strcmp(s, "null")) {
590 json_error(p, "invalid keyword '%s'", s);
593 json_parser_input(p, &token);
597 json_lex_number(struct json_parser *p)
599 const char *cp = ds_cstr(&p->buffer);
600 unsigned long long int significand = 0;
602 bool imprecise = false;
603 bool negative = false;
606 /* Leading minus sign. */
612 /* At least one integer digit, but 0 may not be used as a leading digit for
613 * a longer number. */
619 json_error(p, "leading zeros not allowed");
622 } else if (isdigit(*cp)) {
624 if (significand <= ULLONG_MAX / 10) {
625 significand = significand * 10 + (*cp - '0');
634 } while (isdigit(*cp));
636 json_error(p, "'-' must be followed by digit");
640 /* Optional fraction. */
644 json_error(p, "decimal point must be followed by digit");
648 if (significand <= ULLONG_MAX / 10) {
649 significand = significand * 10 + (*cp - '0');
652 } else if (*cp != '0') {
656 } while (isdigit(*cp));
659 /* Optional exponent. */
660 if (*cp == 'e' || *cp == 'E') {
661 bool negative_exponent = false;
667 } else if (*cp == '-') {
668 negative_exponent = true;
673 json_error(p, "exponent must contain at least one digit");
679 if (exponent >= INT_MAX / 10) {
680 json_error(p, "exponent outside valid range");
683 exponent = exponent * 10 + (*cp - '0');
685 } while (isdigit(*cp));
687 if (negative_exponent) {
695 json_error(p, "syntax error in number");
699 /* Figure out number.
701 * We suppress negative zeros as a matter of policy. */
703 struct json_token token;
704 token.type = T_INTEGER;
706 json_parser_input(p, &token);
711 while (pow10 > 0 && significand < ULLONG_MAX / 10) {
716 while (pow10 < 0 && significand % 10 == 0) {
722 && significand <= (negative
723 ? (unsigned long long int) LLONG_MAX + 1
725 struct json_token token;
726 token.type = T_INTEGER;
727 token.u.integer = negative ? -significand : significand;
728 json_parser_input(p, &token);
733 if (pow10 + sig_digits <= DBL_MAX_10_EXP) {
734 struct json_token token;
736 token.u.real = significand * pow(10.0, pow10);
737 if (token.u.real <= DBL_MAX) {
738 if (negative && token.u.real) {
739 token.u.real = -token.u.real;
741 json_parser_input(p, &token);
745 json_error(p, "number outside valid range");
749 json_lex_4hex(struct json_parser *p, const char *cp, int *valuep)
754 for (i = 0; i < 4; i++) {
755 unsigned char c = *cp++;
757 json_error(p, "malformed \\u escape");
760 value = (value << 4) | hexit_value(c);
763 json_error(p, "null bytes not supported in quoted strings");
771 json_lex_unicode(struct json_parser *p, const char *cp, struct ds *s)
775 if (!json_lex_4hex(p, cp, &c0)) {
779 if (!uc_is_leading_surrogate(c0)) {
784 if (*cp++ != '\\' || *cp++ != 'u') {
785 json_error(p, "malformed escaped surrogate pair");
789 if (!json_lex_4hex(p, cp, &c1)) {
793 if (!uc_is_trailing_surrogate(c1)) {
794 json_error(p, "second half of escaped surrogate pair is not "
795 "trailing surrogate");
799 ds_put_utf8(s, utf16_decode_surrogate_pair(c0, c1));
804 json_lex_string(struct json_parser *p)
806 struct json_token token;
810 cp = ds_cstr(&p->buffer);
811 if (!strchr(cp, '\\')) {
812 token.type = T_STRING;
814 json_parser_input(p, &token);
819 ds_reserve(&s, strlen(cp));
820 while (*cp != '\0') {
822 ds_put_char(&s, *cp++);
828 case '"': case '\\': case '/':
829 ds_put_char(&s, cp[-1]);
833 ds_put_char(&s, '\b');
837 ds_put_char(&s, '\f');
841 ds_put_char(&s, '\n');
845 ds_put_char(&s, '\r');
849 ds_put_char(&s, '\t');
853 cp = json_lex_unicode(p, cp, &s);
860 json_error(p, "bad escape \\%c", cp[-1]);
865 token.type = T_STRING;
866 token.u.string = ds_cstr(&s);
867 json_parser_input(p, &token);
875 json_lex_input(struct json_parser *p, unsigned char c)
877 struct json_token token;
881 p->column_number = 0;
887 switch (p->lex_state) {
890 case ' ': case '\t': case '\n': case '\r':
894 case 'a': case 'b': case 'c': case 'd': case 'e':
895 case 'f': case 'g': case 'h': case 'i': case 'j':
896 case 'k': case 'l': case 'm': case 'n': case 'o':
897 case 'p': case 'q': case 'r': case 's': case 't':
898 case 'u': case 'v': case 'w': case 'x': case 'y':
900 p->lex_state = JSON_LEX_KEYWORD;
903 case '[': case '{': case ']': case '}': case ':': case ',':
905 json_parser_input(p, &token);
909 case '0': case '1': case '2': case '3': case '4':
910 case '5': case '6': case '7': case '8': case '9':
911 p->lex_state = JSON_LEX_NUMBER;
915 p->lex_state = JSON_LEX_STRING;
920 json_error(p, "invalid character '%c'", c);
922 json_error(p, "invalid character U+%04x", c);
928 case JSON_LEX_KEYWORD:
929 if (!isalpha((unsigned char) c)) {
935 case JSON_LEX_NUMBER:
936 if (!strchr(".0123456789eE-+", c)) {
942 case JSON_LEX_STRING:
944 p->lex_state = JSON_LEX_ESCAPE;
945 } else if (c == '"') {
948 } else if (c < 0x20) {
949 json_error(p, "U+%04X must be escaped in quoted string", c);
954 case JSON_LEX_ESCAPE:
955 p->lex_state = JSON_LEX_STRING;
961 ds_put_char(&p->buffer, c);
967 /* Parses 'string' as a JSON object or array and returns a newly allocated
968 * 'struct json'. The caller must free the returned structure with
969 * json_destroy() when it is no longer needed.
971 * 'string' must be encoded in UTF-8.
973 * If 'string' is valid JSON, then the returned 'struct json' will be either an
974 * object (JSON_OBJECT) or an array (JSON_ARRAY).
976 * If 'string' is not valid JSON, then the returned 'struct json' will be a
977 * string (JSON_STRING) that describes the particular error encountered during
978 * parsing. (This is an acceptable means of error reporting because at its top
979 * level JSON must be either an object or an array; a bare string is not
982 json_from_string(const char *string)
984 struct json_parser *p = json_parser_create(JSPF_TRAILER);
985 json_parser_feed(p, string, strlen(string));
986 return json_parser_finish(p);
989 /* Reads the file named 'file_name', parses its contents as a JSON object or
990 * array, and returns a newly allocated 'struct json'. The caller must free
991 * the returned structure with json_destroy() when it is no longer needed.
993 * The file must be encoded in UTF-8.
995 * See json_from_string() for return value semantics.
998 json_from_file(const char *file_name)
1000 struct json_parser *p;
1005 stream = fopen(file_name, "r");
1007 return json_string_create_nocopy(
1008 xasprintf("error opening \"%s\": %s", file_name, strerror(errno)));
1011 /* Read and parse file. */
1012 p = json_parser_create(JSPF_TRAILER);
1014 char buffer[BUFSIZ];
1017 n = fread(buffer, 1, sizeof buffer, stream);
1018 if (!n || json_parser_feed(p, buffer, n) != n) {
1022 json = json_parser_finish(p);
1024 /* Close file and check for I/O errors. */
1025 if (ferror(stream)) {
1027 json = json_string_create_nocopy(
1028 xasprintf("error reading \"%s\": %s", file_name, strerror(errno)));
1035 struct json_parser *
1036 json_parser_create(int flags)
1038 struct json_parser *p = xzalloc(sizeof *p);
1044 json_parser_feed(struct json_parser *p, const char *input, size_t n)
1047 for (i = 0; !p->done && i < n; ) {
1048 if (json_lex_input(p, input[i])) {
1056 json_parser_is_done(const struct json_parser *p)
1062 json_parser_finish(struct json_parser *p)
1066 switch (p->lex_state) {
1067 case JSON_LEX_START:
1070 case JSON_LEX_STRING:
1071 case JSON_LEX_ESCAPE:
1072 json_error(p, "unexpected end of input in quoted string");
1075 case JSON_LEX_NUMBER:
1076 case JSON_LEX_KEYWORD:
1077 json_lex_input(p, ' ');
1081 if (p->parse_state == JSON_PARSE_START) {
1082 json_error(p, "empty input stream");
1083 } else if (p->parse_state != JSON_PARSE_END) {
1084 json_error(p, "unexpected end of input");
1088 assert(p->height == 1);
1089 assert(p->stack[0].json != NULL);
1090 json = p->stack[--p->height].json;
1092 json = json_string_create_nocopy(p->error);
1096 json_parser_abort(p);
1102 json_parser_abort(struct json_parser *p)
1105 ds_destroy(&p->buffer);
1107 json_destroy(p->stack[0].json);
1110 free(p->member_name);
1116 static struct json_parser_node *
1117 json_parser_top(struct json_parser *p)
1119 return &p->stack[p->height - 1];
1123 json_parser_put_value(struct json_parser *p, struct json *value)
1125 struct json_parser_node *node = json_parser_top(p);
1126 if (node->json->type == JSON_OBJECT) {
1127 json_object_put(node->json, p->member_name, value);
1128 free(p->member_name);
1129 p->member_name = NULL;
1130 } else if (node->json->type == JSON_ARRAY) {
1131 json_array_add(node->json, value);
1137 static struct json_parser_node *
1138 json_parser_push(struct json_parser *p,
1139 struct json *new_json, enum json_parse_state new_state)
1141 if (p->height < JSON_MAX_HEIGHT) {
1142 struct json_parser_node *node;
1144 if (p->height >= p->allocated_height) {
1145 p->stack = x2nrealloc(p->stack, &p->allocated_height,
1149 if (p->height > 0) {
1150 json_parser_put_value(p, new_json);
1153 node = &p->stack[p->height++];
1154 node->json = new_json;
1155 p->parse_state = new_state;
1158 json_error(p, "input exceeds maximum nesting depth %d",
1165 json_parser_push_object(struct json_parser *p)
1167 json_parser_push(p, json_object_create(), JSON_PARSE_OBJECT_INIT);
1171 json_parser_push_array(struct json_parser *p)
1173 json_parser_push(p, json_array_create_empty(), JSON_PARSE_ARRAY_INIT);
1177 json_parse_value(struct json_parser *p, struct json_token *token,
1178 enum json_parse_state next_state)
1182 switch (token->type) {
1184 value = json_boolean_create(false);
1188 value = json_null_create();
1192 value = json_boolean_create(true);
1196 json_parser_push_object(p);
1200 json_parser_push_array(p);
1204 value = json_integer_create(token->u.integer);
1208 value = json_real_create(token->u.real);
1212 value = json_string_create(token->u.string);
1221 json_error(p, "syntax error expecting value");
1225 json_parser_put_value(p, value);
1226 p->parse_state = next_state;
1230 json_parser_pop(struct json_parser *p)
1232 struct json_parser_node *node;
1234 /* Conserve memory. */
1235 node = json_parser_top(p);
1236 if (node->json->type == JSON_ARRAY) {
1237 json_array_trim(node->json);
1240 /* Pop off the top-of-stack. */
1241 if (p->height == 1) {
1242 p->parse_state = JSON_PARSE_END;
1243 if (!(p->flags & JSPF_TRAILER)) {
1248 node = json_parser_top(p);
1249 if (node->json->type == JSON_ARRAY) {
1250 p->parse_state = JSON_PARSE_ARRAY_NEXT;
1251 } else if (node->json->type == JSON_OBJECT) {
1252 p->parse_state = JSON_PARSE_OBJECT_NEXT;
1260 json_parser_input(struct json_parser *p, struct json_token *token)
1262 switch (p->parse_state) {
1263 case JSON_PARSE_START:
1264 if (token->type == '{') {
1265 json_parser_push_object(p);
1266 } else if (token->type == '[') {
1267 json_parser_push_array(p);
1269 json_error(p, "syntax error at beginning of input");
1273 case JSON_PARSE_END:
1274 json_error(p, "trailing garbage at end of input");
1277 case JSON_PARSE_OBJECT_INIT:
1278 if (token->type == '}') {
1283 case JSON_PARSE_OBJECT_NAME:
1284 if (token->type == T_STRING) {
1285 p->member_name = xstrdup(token->u.string);
1286 p->parse_state = JSON_PARSE_OBJECT_COLON;
1288 json_error(p, "syntax error parsing object expecting string");
1292 case JSON_PARSE_OBJECT_COLON:
1293 if (token->type == ':') {
1294 p->parse_state = JSON_PARSE_OBJECT_VALUE;
1296 json_error(p, "syntax error parsing object expecting ':'");
1300 case JSON_PARSE_OBJECT_VALUE:
1301 json_parse_value(p, token, JSON_PARSE_OBJECT_NEXT);
1304 case JSON_PARSE_OBJECT_NEXT:
1305 if (token->type == ',') {
1306 p->parse_state = JSON_PARSE_OBJECT_NAME;
1307 } else if (token->type == '}') {
1310 json_error(p, "syntax error expecting '}' or ','");
1314 case JSON_PARSE_ARRAY_INIT:
1315 if (token->type == ']') {
1320 case JSON_PARSE_ARRAY_VALUE:
1321 json_parse_value(p, token, JSON_PARSE_ARRAY_NEXT);
1324 case JSON_PARSE_ARRAY_NEXT:
1325 if (token->type == ',') {
1326 p->parse_state = JSON_PARSE_ARRAY_VALUE;
1327 } else if (token->type == ']') {
1330 json_error(p, "syntax error expecting ']' or ','");
1338 p->lex_state = JSON_LEX_START;
1339 ds_clear(&p->buffer);
1342 static struct json *
1343 json_create(enum json_type type)
1345 struct json *json = xmalloc(sizeof *json);
1351 json_error(struct json_parser *p, const char *format, ...)
1358 ds_put_format(&msg, "line %d, column %d, byte %d: ",
1359 p->line_number, p->column_number, p->byte_number);
1360 va_start(args, format);
1361 ds_put_format_valist(&msg, format, args);
1364 p->error = ds_steal_cstr(&msg);
1370 #define SPACES_PER_LEVEL 2
1372 struct json_serializer {
1378 static void json_to_ds(const struct json *, struct json_serializer *);
1379 static void json_object_to_ds(const struct shash *object,
1380 struct json_serializer *);
1381 static void json_array_to_ds(const struct json_array *,
1382 struct json_serializer *);
1383 static void json_string_to_ds(const char *string, struct ds *);
1385 /* Converts 'json' to a string in JSON format, encoded in UTF-8, and returns
1386 * that string. The caller is responsible for freeing the returned string,
1387 * with free(), when it is no longer needed.
1389 * If 'flags' contains JSSF_PRETTY, the output is pretty-printed with each
1390 * nesting level introducing an additional indentation. Otherwise, the
1391 * returned string does not contain any new-line characters.
1393 * If 'flags' contains JSSF_SORT, members of objects in the output are sorted
1394 * in bytewise lexicographic order for reproducibility. Otherwise, members of
1395 * objects are output in an indeterminate order.
1397 * The returned string is valid JSON only if 'json' represents an array or an
1398 * object, since a bare literal does not satisfy the JSON grammar. */
1400 json_to_string(const struct json *json, int flags)
1402 struct json_serializer s;
1406 json_to_ds(json, &s);
1407 return ds_steal_cstr(&s.ds);
1411 json_to_ds(const struct json *json, struct json_serializer *s)
1413 struct ds *ds = &s->ds;
1415 switch (json->type) {
1417 ds_put_cstr(ds, "null");
1421 ds_put_cstr(ds, "false");
1425 ds_put_cstr(ds, "true");
1429 json_object_to_ds(json->u.object, s);
1433 json_array_to_ds(&json->u.array, s);
1437 ds_put_format(ds, "%lld", json->u.integer);
1441 ds_put_format(ds, "%.*g", DBL_DIG, json->u.real);
1445 json_string_to_ds(json->u.string, ds);
1455 indent_line(struct json_serializer *s)
1457 if (s->flags & JSSF_PRETTY) {
1458 ds_put_char(&s->ds, '\n');
1459 ds_put_char_multiple(&s->ds, ' ', SPACES_PER_LEVEL * s->depth);
1464 json_object_member_to_ds(size_t i, const struct shash_node *node,
1465 struct json_serializer *s)
1467 struct ds *ds = &s->ds;
1470 ds_put_char(ds, ',');
1474 json_string_to_ds(node->name, ds);
1475 ds_put_char(ds, ':');
1476 if (s->flags & JSSF_PRETTY) {
1477 ds_put_char(ds, ' ');
1479 json_to_ds(node->data, s);
1483 json_object_to_ds(const struct shash *object, struct json_serializer *s)
1485 struct ds *ds = &s->ds;
1487 ds_put_char(ds, '{');
1492 if (s->flags & JSSF_SORT) {
1493 const struct shash_node **nodes;
1496 nodes = shash_sort(object);
1497 n = shash_count(object);
1498 for (i = 0; i < n; i++) {
1499 json_object_member_to_ds(i, nodes[i], s);
1503 struct shash_node *node;
1507 SHASH_FOR_EACH (node, object) {
1508 json_object_member_to_ds(i++, node, s);
1512 ds_put_char(ds, '}');
1517 json_array_to_ds(const struct json_array *array, struct json_serializer *s)
1519 struct ds *ds = &s->ds;
1522 ds_put_char(ds, '[');
1528 for (i = 0; i < array->n; i++) {
1530 ds_put_char(ds, ',');
1533 json_to_ds(array->elems[i], s);
1538 ds_put_char(ds, ']');
1542 json_string_to_ds(const char *string, struct ds *ds)
1546 ds_put_char(ds, '"');
1547 while ((c = *string++) != '\0') {
1550 ds_put_cstr(ds, "\\\"");
1554 ds_put_cstr(ds, "\\\\");
1558 ds_put_cstr(ds, "\\b");
1562 ds_put_cstr(ds, "\\f");
1566 ds_put_cstr(ds, "\\n");
1570 ds_put_cstr(ds, "\\r");
1574 ds_put_cstr(ds, "\\t");
1581 ds_put_format(ds, "\\u%04x", c);
1586 ds_put_char(ds, '"');