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. */
104 enum json_parse_state parse_state
;
105 #define JSON_MAX_HEIGHT 1000
106 struct json_parser_node
*stack
;
107 size_t height
, allocated_height
;
112 char *error
; /* Error message, if any, null if none yet. */
115 static struct json
*json_create(enum json_type type
);
116 static void json_parser_input(struct json_parser
*, struct json_token
*);
118 static void json_error(struct json_parser
*p
, const char *format
, ...)
122 json_type_to_string(enum json_type type
)
153 /* Functions for manipulating struct json. */
156 json_null_create(void)
158 return json_create(JSON_NULL
);
162 json_boolean_create(bool b
)
164 return json_create(b
? JSON_TRUE
: JSON_FALSE
);
168 json_string_create_nocopy(char *s
)
170 struct json
*json
= json_create(JSON_STRING
);
176 json_string_create(const char *s
)
178 return json_string_create_nocopy(xstrdup(s
));
182 json_array_create_empty(void)
184 struct json
*json
= json_create(JSON_ARRAY
);
185 json
->u
.array
.elems
= NULL
;
187 json
->u
.array
.n_allocated
= 0;
192 json_array_add(struct json
*array_
, struct json
*element
)
194 struct json_array
*array
= json_array(array_
);
195 if (array
->n
>= array
->n_allocated
) {
196 array
->elems
= x2nrealloc(array
->elems
, &array
->n_allocated
,
197 sizeof *array
->elems
);
199 array
->elems
[array
->n
++] = element
;
203 json_array_trim(struct json
*array_
)
205 struct json_array
*array
= json_array(array_
);
206 if (array
->n
< array
->n_allocated
){
207 array
->n_allocated
= array
->n
;
208 array
->elems
= xrealloc(array
->elems
, array
->n
* sizeof *array
->elems
);
213 json_array_create(struct json
**elements
, size_t n
)
215 struct json
*json
= json_create(JSON_ARRAY
);
216 json
->u
.array
.elems
= elements
;
218 json
->u
.array
.n_allocated
= n
;
223 json_array_create_2(struct json
*elem0
, struct json
*elem1
)
225 struct json
**elems
= xmalloc(2 * sizeof *elems
);
228 return json_array_create(elems
, 2);
232 json_array_create_3(struct json
*elem0
, struct json
*elem1
, struct json
*elem2
)
234 struct json
**elems
= xmalloc(3 * sizeof *elems
);
238 return json_array_create(elems
, 3);
242 json_object_create(void)
244 struct json
*json
= json_create(JSON_OBJECT
);
245 json
->u
.object
= xmalloc(sizeof *json
->u
.object
);
246 shash_init(json
->u
.object
);
251 json_integer_create(long long int integer
)
253 struct json
*json
= json_create(JSON_INTEGER
);
254 json
->u
.integer
= integer
;
259 json_real_create(double real
)
261 struct json
*json
= json_create(JSON_REAL
);
267 json_object_put(struct json
*json
, const char *name
, struct json
*value
)
269 shash_add(json
->u
.object
, name
, value
);
273 json_object_put_string(struct json
*json
, const char *name
, const char *value
)
275 json_object_put(json
, name
, json_string_create(value
));
279 json_string(const struct json
*json
)
281 assert(json
->type
== JSON_STRING
);
282 return json
->u
.string
;
286 json_array(const struct json
*json
)
288 assert(json
->type
== JSON_ARRAY
);
289 return (struct json_array
*) &json
->u
.array
;
293 json_object(const struct json
*json
)
295 assert(json
->type
== JSON_OBJECT
);
296 return (struct shash
*) json
->u
.object
;
300 json_boolean(const struct json
*json
)
302 assert(json
->type
== JSON_TRUE
|| json
->type
== JSON_FALSE
);
303 return json
->type
== JSON_TRUE
;
307 json_real(const struct json
*json
)
309 assert(json
->type
== JSON_REAL
|| json
->type
== JSON_INTEGER
);
310 return json
->type
== JSON_REAL
? json
->u
.real
: json
->u
.integer
;
314 json_integer(const struct json
*json
)
316 assert(json
->type
== JSON_INTEGER
);
317 return json
->u
.integer
;
320 static void json_destroy_object(struct shash
*object
);
321 static void json_destroy_array(struct json_array
*array
);
323 /* Frees 'json' and everything it points to, recursively. */
325 json_destroy(struct json
*json
)
328 switch (json
->type
) {
330 json_destroy_object(json
->u
.object
);
334 json_destroy_array(&json
->u
.array
);
338 free(json
->u
.string
);
356 json_destroy_object(struct shash
*object
)
358 struct shash_node
*node
, *next
;
360 SHASH_FOR_EACH_SAFE (node
, next
, object
) {
361 struct json
*value
= node
->data
;
364 shash_delete(object
, node
);
366 shash_destroy(object
);
371 json_destroy_array(struct json_array
*array
)
375 for (i
= 0; i
< array
->n
; i
++) {
376 json_destroy(array
->elems
[i
]);
381 static struct json
*json_clone_object(const struct shash
*object
);
382 static struct json
*json_clone_array(const struct json_array
*array
);
384 /* Returns a deep copy of 'json'. */
386 json_clone(const struct json
*json
)
388 switch (json
->type
) {
390 return json_clone_object(json
->u
.object
);
393 return json_clone_array(&json
->u
.array
);
396 return json_string_create(json
->u
.string
);
401 return json_create(json
->type
);
404 return json_integer_create(json
->u
.integer
);
407 return json_real_create(json
->u
.real
);
416 json_clone_object(const struct shash
*object
)
418 struct shash_node
*node
;
421 json
= json_object_create();
422 SHASH_FOR_EACH (node
, object
) {
423 struct json
*value
= node
->data
;
424 json_object_put(json
, node
->name
, json_clone(value
));
430 json_clone_array(const struct json_array
*array
)
435 elems
= xmalloc(array
->n
* sizeof *elems
);
436 for (i
= 0; i
< array
->n
; i
++) {
437 elems
[i
] = json_clone(array
->elems
[i
]);
439 return json_array_create(elems
, array
->n
);
443 json_hash_object(const struct shash
*object
, size_t basis
)
445 const struct shash_node
**nodes
;
448 nodes
= shash_sort(object
);
449 n
= shash_count(object
);
450 for (i
= 0; i
< n
; i
++) {
451 const struct shash_node
*node
= nodes
[i
];
452 basis
= hash_string(node
->name
, basis
);
453 basis
= json_hash(node
->data
, basis
);
459 json_hash_array(const struct json_array
*array
, size_t basis
)
463 basis
= hash_int(array
->n
, basis
);
464 for (i
= 0; i
< array
->n
; i
++) {
465 basis
= json_hash(array
->elems
[i
], basis
);
471 json_hash(const struct json
*json
, size_t basis
)
473 switch (json
->type
) {
475 return json_hash_object(json
->u
.object
, basis
);
478 return json_hash_array(&json
->u
.array
, basis
);
481 return hash_string(json
->u
.string
, basis
);
486 return hash_int(json
->type
<< 8, basis
);
489 return hash_int(json
->u
.integer
, basis
);
492 return hash_double(json
->u
.real
, basis
);
501 json_equal_object(const struct shash
*a
, const struct shash
*b
)
503 struct shash_node
*node
;
505 if (shash_count(a
) != shash_count(b
)) {
509 SHASH_FOR_EACH (node
, a
) {
510 if (!shash_find(b
, node
->name
)) {
519 json_equal_array(const struct json_array
*a
, const struct json_array
*b
)
527 for (i
= 0; i
< a
->n
; i
++) {
528 if (!json_equal(a
->elems
[i
], b
->elems
[i
])) {
537 json_equal(const struct json
*a
, const struct json
*b
)
539 if (a
->type
!= b
->type
) {
545 return json_equal_object(a
->u
.object
, b
->u
.object
);
548 return json_equal_array(&a
->u
.array
, &b
->u
.array
);
551 return !strcmp(a
->u
.string
, b
->u
.string
);
559 return a
->u
.integer
== b
->u
.integer
;
562 return a
->u
.real
== b
->u
.real
;
570 /* Lexical analysis. */
573 json_lex_keyword(struct json_parser
*p
)
575 struct json_token token
;
578 s
= ds_cstr(&p
->buffer
);
579 if (!strcmp(s
, "false")) {
580 token
.type
= T_FALSE
;
581 } else if (!strcmp(s
, "true")) {
583 } else if (!strcmp(s
, "null")) {
586 json_error(p
, "invalid keyword '%s'", s
);
589 json_parser_input(p
, &token
);
593 json_lex_number(struct json_parser
*p
)
595 const char *cp
= ds_cstr(&p
->buffer
);
596 unsigned long long int significand
= 0;
598 bool imprecise
= false;
599 bool negative
= false;
602 /* Leading minus sign. */
608 /* At least one integer digit, but 0 may not be used as a leading digit for
609 * a longer number. */
615 json_error(p
, "leading zeros not allowed");
618 } else if (isdigit(*cp
)) {
620 if (significand
<= ULLONG_MAX
/ 10) {
621 significand
= significand
* 10 + (*cp
- '0');
630 } while (isdigit(*cp
));
632 json_error(p
, "'-' must be followed by digit");
636 /* Optional fraction. */
640 json_error(p
, "decimal point must be followed by digit");
644 if (significand
<= ULLONG_MAX
/ 10) {
645 significand
= significand
* 10 + (*cp
- '0');
648 } else if (*cp
!= '0') {
652 } while (isdigit(*cp
));
655 /* Optional exponent. */
656 if (*cp
== 'e' || *cp
== 'E') {
657 bool negative_exponent
= false;
663 } else if (*cp
== '-') {
664 negative_exponent
= true;
669 json_error(p
, "exponent must contain at least one digit");
675 if (exponent
>= INT_MAX
/ 10) {
676 json_error(p
, "exponent outside valid range");
679 exponent
= exponent
* 10 + (*cp
- '0');
681 } while (isdigit(*cp
));
683 if (negative_exponent
) {
691 json_error(p
, "syntax error in number");
695 /* Figure out number.
697 * We suppress negative zeros as a matter of policy. */
699 struct json_token token
;
700 token
.type
= T_INTEGER
;
702 json_parser_input(p
, &token
);
707 while (pow10
> 0 && significand
< ULLONG_MAX
/ 10) {
712 while (pow10
< 0 && significand
% 10 == 0) {
718 && significand
<= (negative
719 ? (unsigned long long int) LLONG_MAX
+ 1
721 struct json_token token
;
722 token
.type
= T_INTEGER
;
723 token
.u
.integer
= negative
? -significand
: significand
;
724 json_parser_input(p
, &token
);
729 if (pow10
+ sig_digits
<= DBL_MAX_10_EXP
) {
730 struct json_token token
;
732 token
.u
.real
= significand
* pow(10.0, pow10
);
733 if (token
.u
.real
<= DBL_MAX
) {
734 if (negative
&& token
.u
.real
) {
735 token
.u
.real
= -token
.u
.real
;
737 json_parser_input(p
, &token
);
741 json_error(p
, "number outside valid range");
745 json_lex_4hex(struct json_parser
*p
, const char *cp
, int *valuep
)
750 for (i
= 0; i
< 4; i
++) {
751 unsigned char c
= *cp
++;
753 json_error(p
, "malformed \\u escape");
756 value
= (value
<< 4) | hexit_value(c
);
759 json_error(p
, "null bytes not supported in quoted strings");
767 json_lex_unicode(struct json_parser
*p
, const char *cp
, struct ds
*s
)
771 if (!json_lex_4hex(p
, cp
, &c0
)) {
775 if (!uc_is_leading_surrogate(c0
)) {
780 if (*cp
++ != '\\' || *cp
++ != 'u') {
781 json_error(p
, "malformed escaped surrogate pair");
785 if (!json_lex_4hex(p
, cp
, &c1
)) {
789 if (!uc_is_trailing_surrogate(c1
)) {
790 json_error(p
, "second half of escaped surrogate pair is not "
791 "trailing surrogate");
795 ds_put_utf8(s
, utf16_decode_surrogate_pair(c0
, c1
));
800 json_lex_string(struct json_parser
*p
)
802 struct json_token token
;
806 cp
= ds_cstr(&p
->buffer
);
807 if (!strchr(cp
, '\\')) {
808 token
.type
= T_STRING
;
810 json_parser_input(p
, &token
);
815 ds_reserve(&s
, strlen(cp
));
816 while (*cp
!= '\0') {
818 ds_put_char(&s
, *cp
++);
824 case '"': case '\\': case '/':
825 ds_put_char(&s
, cp
[-1]);
829 ds_put_char(&s
, '\b');
833 ds_put_char(&s
, '\f');
837 ds_put_char(&s
, '\n');
841 ds_put_char(&s
, '\r');
845 ds_put_char(&s
, '\t');
849 cp
= json_lex_unicode(p
, cp
, &s
);
856 json_error(p
, "bad escape \\%c", cp
[-1]);
861 token
.type
= T_STRING
;
862 token
.u
.string
= ds_cstr(&s
);
863 json_parser_input(p
, &token
);
871 json_lex_input(struct json_parser
*p
, int c
)
873 struct json_token token
;
875 switch (p
->lex_state
) {
878 case ' ': case '\t': case '\n': case '\r':
882 case 'a': case 'b': case 'c': case 'd': case 'e':
883 case 'f': case 'g': case 'h': case 'i': case 'j':
884 case 'k': case 'l': case 'm': case 'n': case 'o':
885 case 'p': case 'q': case 'r': case 's': case 't':
886 case 'u': case 'v': case 'w': case 'x': case 'y':
888 p
->lex_state
= JSON_LEX_KEYWORD
;
891 case '[': case '{': case ']': case '}': case ':': case ',':
893 json_parser_input(p
, &token
);
897 case '0': case '1': case '2': case '3': case '4':
898 case '5': case '6': case '7': case '8': case '9':
899 p
->lex_state
= JSON_LEX_NUMBER
;
903 p
->lex_state
= JSON_LEX_STRING
;
908 json_error(p
, "invalid character '%c'", c
);
910 json_error(p
, "invalid character U+%04x", c
);
916 case JSON_LEX_KEYWORD
:
917 if (!isalpha((unsigned char) c
)) {
923 case JSON_LEX_NUMBER
:
924 if (!strchr(".0123456789eE-+", c
)) {
930 case JSON_LEX_STRING
:
932 p
->lex_state
= JSON_LEX_ESCAPE
;
933 } else if (c
== '"') {
936 } else if (c
< 0x20) {
937 json_error(p
, "U+%04X must be escaped in quoted string", c
);
942 case JSON_LEX_ESCAPE
:
943 p
->lex_state
= JSON_LEX_STRING
;
949 ds_put_char(&p
->buffer
, c
);
955 /* Parses 'string' as a JSON object or array and returns a newly allocated
956 * 'struct json'. The caller must free the returned structure with
957 * json_destroy() when it is no longer needed.
959 * 'string' must be encoded in UTF-8.
961 * If 'string' is valid JSON, then the returned 'struct json' will be either an
962 * object (JSON_OBJECT) or an array (JSON_ARRAY).
964 * If 'string' is not valid JSON, then the returned 'struct json' will be a
965 * string (JSON_STRING) that describes the particular error encountered during
966 * parsing. (This is an acceptable means of error reporting because at its top
967 * level JSON must be either an object or an array; a bare string is not
970 json_from_string(const char *string
)
972 struct json_parser
*p
= json_parser_create(JSPF_TRAILER
);
973 json_parser_feed(p
, string
, strlen(string
));
974 return json_parser_finish(p
);
977 /* Reads the file named 'file_name', parses its contents as a JSON object or
978 * array, and returns a newly allocated 'struct json'. The caller must free
979 * the returned structure with json_destroy() when it is no longer needed.
981 * The file must be encoded in UTF-8.
983 * See json_from_string() for return value semantics.
986 json_from_file(const char *file_name
)
988 struct json_parser
*p
;
993 stream
= fopen(file_name
, "r");
995 return json_string_create_nocopy(
996 xasprintf("error opening \"%s\": %s", file_name
, strerror(errno
)));
999 /* Read and parse file. */
1000 p
= json_parser_create(JSPF_TRAILER
);
1002 char buffer
[BUFSIZ
];
1005 n
= fread(buffer
, 1, sizeof buffer
, stream
);
1006 if (!n
|| json_parser_feed(p
, buffer
, n
) != n
) {
1010 json
= json_parser_finish(p
);
1012 /* Close file and check for I/O errors. */
1013 if (ferror(stream
)) {
1015 json
= json_string_create_nocopy(
1016 xasprintf("error reading \"%s\": %s", file_name
, strerror(errno
)));
1023 struct json_parser
*
1024 json_parser_create(int flags
)
1026 struct json_parser
*p
= xzalloc(sizeof *p
);
1032 json_parser_feed(struct json_parser
*p
, const char *input
, size_t n
)
1035 for (i
= 0; !p
->done
&& i
< n
; ) {
1036 if (json_lex_input(p
, input
[i
])) {
1044 json_parser_is_done(const struct json_parser
*p
)
1050 json_parser_finish(struct json_parser
*p
)
1054 switch (p
->lex_state
) {
1055 case JSON_LEX_START
:
1058 case JSON_LEX_STRING
:
1059 case JSON_LEX_ESCAPE
:
1060 json_error(p
, "unexpected end of input in quoted string");
1063 case JSON_LEX_NUMBER
:
1064 case JSON_LEX_KEYWORD
:
1065 json_lex_input(p
, ' ');
1069 if (p
->parse_state
== JSON_PARSE_START
) {
1070 json_error(p
, "empty input stream");
1071 } else if (p
->parse_state
!= JSON_PARSE_END
) {
1072 json_error(p
, "unexpected end of input");
1076 assert(p
->height
== 1);
1077 assert(p
->stack
[0].json
!= NULL
);
1078 json
= p
->stack
[--p
->height
].json
;
1080 json
= json_string_create_nocopy(p
->error
);
1084 json_parser_abort(p
);
1090 json_parser_abort(struct json_parser
*p
)
1093 ds_destroy(&p
->buffer
);
1095 json_destroy(p
->stack
[0].json
);
1098 free(p
->member_name
);
1104 static struct json_parser_node
*
1105 json_parser_top(struct json_parser
*p
)
1107 return &p
->stack
[p
->height
- 1];
1111 json_parser_put_value(struct json_parser
*p
, struct json
*value
)
1113 struct json_parser_node
*node
= json_parser_top(p
);
1114 if (node
->json
->type
== JSON_OBJECT
) {
1115 json_object_put(node
->json
, p
->member_name
, value
);
1116 free(p
->member_name
);
1117 p
->member_name
= NULL
;
1118 } else if (node
->json
->type
== JSON_ARRAY
) {
1119 json_array_add(node
->json
, value
);
1125 static struct json_parser_node
*
1126 json_parser_push(struct json_parser
*p
,
1127 struct json
*new_json
, enum json_parse_state new_state
)
1129 if (p
->height
< JSON_MAX_HEIGHT
) {
1130 struct json_parser_node
*node
;
1132 if (p
->height
>= p
->allocated_height
) {
1133 p
->stack
= x2nrealloc(p
->stack
, &p
->allocated_height
,
1137 if (p
->height
> 0) {
1138 json_parser_put_value(p
, new_json
);
1141 node
= &p
->stack
[p
->height
++];
1142 node
->json
= new_json
;
1143 p
->parse_state
= new_state
;
1146 json_error(p
, "input exceeds maximum nesting depth %d",
1153 json_parser_push_object(struct json_parser
*p
)
1155 json_parser_push(p
, json_object_create(), JSON_PARSE_OBJECT_INIT
);
1159 json_parser_push_array(struct json_parser
*p
)
1161 json_parser_push(p
, json_array_create_empty(), JSON_PARSE_ARRAY_INIT
);
1165 json_parse_value(struct json_parser
*p
, struct json_token
*token
,
1166 enum json_parse_state next_state
)
1170 switch (token
->type
) {
1172 value
= json_boolean_create(false);
1176 value
= json_null_create();
1180 value
= json_boolean_create(true);
1184 json_parser_push_object(p
);
1188 json_parser_push_array(p
);
1192 value
= json_integer_create(token
->u
.integer
);
1196 value
= json_real_create(token
->u
.real
);
1200 value
= json_string_create(token
->u
.string
);
1209 json_error(p
, "syntax error expecting value");
1213 json_parser_put_value(p
, value
);
1214 p
->parse_state
= next_state
;
1218 json_parser_pop(struct json_parser
*p
)
1220 struct json_parser_node
*node
;
1222 /* Conserve memory. */
1223 node
= json_parser_top(p
);
1224 if (node
->json
->type
== JSON_ARRAY
) {
1225 json_array_trim(node
->json
);
1228 /* Pop off the top-of-stack. */
1229 if (p
->height
== 1) {
1230 p
->parse_state
= JSON_PARSE_END
;
1231 if (!(p
->flags
& JSPF_TRAILER
)) {
1236 node
= json_parser_top(p
);
1237 if (node
->json
->type
== JSON_ARRAY
) {
1238 p
->parse_state
= JSON_PARSE_ARRAY_NEXT
;
1239 } else if (node
->json
->type
== JSON_OBJECT
) {
1240 p
->parse_state
= JSON_PARSE_OBJECT_NEXT
;
1248 json_parser_input(struct json_parser
*p
, struct json_token
*token
)
1250 switch (p
->parse_state
) {
1251 case JSON_PARSE_START
:
1252 if (token
->type
== '{') {
1253 json_parser_push_object(p
);
1254 } else if (token
->type
== '[') {
1255 json_parser_push_array(p
);
1257 json_error(p
, "syntax error at beginning of input");
1261 case JSON_PARSE_END
:
1262 json_error(p
, "trailing garbage at end of input");
1265 case JSON_PARSE_OBJECT_INIT
:
1266 if (token
->type
== '}') {
1271 case JSON_PARSE_OBJECT_NAME
:
1272 if (token
->type
== T_STRING
) {
1273 p
->member_name
= xstrdup(token
->u
.string
);
1274 p
->parse_state
= JSON_PARSE_OBJECT_COLON
;
1276 json_error(p
, "syntax error parsing object expecting string");
1280 case JSON_PARSE_OBJECT_COLON
:
1281 if (token
->type
== ':') {
1282 p
->parse_state
= JSON_PARSE_OBJECT_VALUE
;
1284 json_error(p
, "syntax error parsing object expecting ':'");
1288 case JSON_PARSE_OBJECT_VALUE
:
1289 json_parse_value(p
, token
, JSON_PARSE_OBJECT_NEXT
);
1292 case JSON_PARSE_OBJECT_NEXT
:
1293 if (token
->type
== ',') {
1294 p
->parse_state
= JSON_PARSE_OBJECT_NAME
;
1295 } else if (token
->type
== '}') {
1298 json_error(p
, "syntax error expecting '}' or ','");
1302 case JSON_PARSE_ARRAY_INIT
:
1303 if (token
->type
== ']') {
1308 case JSON_PARSE_ARRAY_VALUE
:
1309 json_parse_value(p
, token
, JSON_PARSE_ARRAY_NEXT
);
1312 case JSON_PARSE_ARRAY_NEXT
:
1313 if (token
->type
== ',') {
1314 p
->parse_state
= JSON_PARSE_ARRAY_VALUE
;
1315 } else if (token
->type
== ']') {
1318 json_error(p
, "syntax error expecting ']' or ','");
1326 p
->lex_state
= JSON_LEX_START
;
1327 ds_clear(&p
->buffer
);
1330 static struct json
*
1331 json_create(enum json_type type
)
1333 struct json
*json
= xmalloc(sizeof *json
);
1339 json_error(struct json_parser
*p
, const char *format
, ...)
1344 va_start(args
, format
);
1345 p
->error
= xvasprintf(format
, args
);
1352 #define SPACES_PER_LEVEL 2
1354 struct json_serializer
{
1360 static void json_to_ds(const struct json
*, struct json_serializer
*);
1361 static void json_object_to_ds(const struct shash
*object
,
1362 struct json_serializer
*);
1363 static void json_array_to_ds(const struct json_array
*,
1364 struct json_serializer
*);
1365 static void json_string_to_ds(const char *string
, struct ds
*);
1367 /* Converts 'json' to a string in JSON format, encoded in UTF-8, and returns
1368 * that string. The caller is responsible for freeing the returned string,
1369 * with free(), when it is no longer needed.
1371 * If 'flags' contains JSSF_PRETTY, the output is pretty-printed with each
1372 * nesting level introducing an additional indentation. Otherwise, the
1373 * returned string does not contain any new-line characters.
1375 * If 'flags' contains JSSF_SORT, members of objects in the output are sorted
1376 * in bytewise lexicographic order for reproducibility. Otherwise, members of
1377 * objects are output in an indeterminate order.
1379 * The returned string is valid JSON only if 'json' represents an array or an
1380 * object, since a bare literal does not satisfy the JSON grammar. */
1382 json_to_string(const struct json
*json
, int flags
)
1384 struct json_serializer s
;
1388 json_to_ds(json
, &s
);
1389 return ds_steal_cstr(&s
.ds
);
1393 json_to_ds(const struct json
*json
, struct json_serializer
*s
)
1395 struct ds
*ds
= &s
->ds
;
1397 switch (json
->type
) {
1399 ds_put_cstr(ds
, "null");
1403 ds_put_cstr(ds
, "false");
1407 ds_put_cstr(ds
, "true");
1411 json_object_to_ds(json
->u
.object
, s
);
1415 json_array_to_ds(&json
->u
.array
, s
);
1419 ds_put_format(ds
, "%lld", json
->u
.integer
);
1423 ds_put_format(ds
, "%.*g", DBL_DIG
, json
->u
.real
);
1427 json_string_to_ds(json
->u
.string
, ds
);
1437 indent_line(struct json_serializer
*s
)
1439 if (s
->flags
& JSSF_PRETTY
) {
1440 ds_put_char(&s
->ds
, '\n');
1441 ds_put_char_multiple(&s
->ds
, ' ', SPACES_PER_LEVEL
* s
->depth
);
1446 json_object_member_to_ds(size_t i
, const struct shash_node
*node
,
1447 struct json_serializer
*s
)
1449 struct ds
*ds
= &s
->ds
;
1452 ds_put_char(ds
, ',');
1456 json_string_to_ds(node
->name
, ds
);
1457 ds_put_char(ds
, ':');
1458 if (s
->flags
& JSSF_PRETTY
) {
1459 ds_put_char(ds
, ' ');
1461 json_to_ds(node
->data
, s
);
1465 json_object_to_ds(const struct shash
*object
, struct json_serializer
*s
)
1467 struct ds
*ds
= &s
->ds
;
1469 ds_put_char(ds
, '{');
1474 if (s
->flags
& JSSF_SORT
) {
1475 const struct shash_node
**nodes
;
1478 nodes
= shash_sort(object
);
1479 n
= shash_count(object
);
1480 for (i
= 0; i
< n
; i
++) {
1481 json_object_member_to_ds(i
, nodes
[i
], s
);
1485 struct shash_node
*node
;
1489 SHASH_FOR_EACH (node
, object
) {
1490 json_object_member_to_ds(i
++, node
, s
);
1494 ds_put_char(ds
, '}');
1499 json_array_to_ds(const struct json_array
*array
, struct json_serializer
*s
)
1501 struct ds
*ds
= &s
->ds
;
1504 ds_put_char(ds
, '[');
1510 for (i
= 0; i
< array
->n
; i
++) {
1512 ds_put_char(ds
, ',');
1515 json_to_ds(array
->elems
[i
], s
);
1520 ds_put_char(ds
, ']');
1524 json_string_to_ds(const char *string
, struct ds
*ds
)
1528 ds_put_char(ds
, '"');
1529 while ((c
= *string
++) != '\0') {
1532 ds_put_cstr(ds
, "\\\"");
1536 ds_put_cstr(ds
, "\\\\");
1540 ds_put_cstr(ds
, "\\b");
1544 ds_put_cstr(ds
, "\\f");
1548 ds_put_cstr(ds
, "\\n");
1552 ds_put_cstr(ds
, "\\r");
1556 ds_put_cstr(ds
, "\\t");
1563 ds_put_format(ds
, "\\u%04x", c
);
1568 ds_put_char(ds
, '"');