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
*a_node
;
505 if (shash_count(a
) != shash_count(b
)) {
509 SHASH_FOR_EACH (a_node
, a
) {
510 struct shash_node
*b_node
= shash_find(b
, a_node
->name
);
511 if (!b_node
|| !json_equal(a_node
->data
, b_node
->data
)) {
520 json_equal_array(const struct json_array
*a
, const struct json_array
*b
)
528 for (i
= 0; i
< a
->n
; i
++) {
529 if (!json_equal(a
->elems
[i
], b
->elems
[i
])) {
538 json_equal(const struct json
*a
, const struct json
*b
)
540 if (a
->type
!= b
->type
) {
546 return json_equal_object(a
->u
.object
, b
->u
.object
);
549 return json_equal_array(&a
->u
.array
, &b
->u
.array
);
552 return !strcmp(a
->u
.string
, b
->u
.string
);
560 return a
->u
.integer
== b
->u
.integer
;
563 return a
->u
.real
== b
->u
.real
;
571 /* Lexical analysis. */
574 json_lex_keyword(struct json_parser
*p
)
576 struct json_token token
;
579 s
= ds_cstr(&p
->buffer
);
580 if (!strcmp(s
, "false")) {
581 token
.type
= T_FALSE
;
582 } else if (!strcmp(s
, "true")) {
584 } else if (!strcmp(s
, "null")) {
587 json_error(p
, "invalid keyword '%s'", s
);
590 json_parser_input(p
, &token
);
594 json_lex_number(struct json_parser
*p
)
596 const char *cp
= ds_cstr(&p
->buffer
);
597 unsigned long long int significand
= 0;
599 bool imprecise
= false;
600 bool negative
= false;
603 /* Leading minus sign. */
609 /* At least one integer digit, but 0 may not be used as a leading digit for
610 * a longer number. */
616 json_error(p
, "leading zeros not allowed");
619 } else if (isdigit(*cp
)) {
621 if (significand
<= ULLONG_MAX
/ 10) {
622 significand
= significand
* 10 + (*cp
- '0');
631 } while (isdigit(*cp
));
633 json_error(p
, "'-' must be followed by digit");
637 /* Optional fraction. */
641 json_error(p
, "decimal point must be followed by digit");
645 if (significand
<= ULLONG_MAX
/ 10) {
646 significand
= significand
* 10 + (*cp
- '0');
649 } else if (*cp
!= '0') {
653 } while (isdigit(*cp
));
656 /* Optional exponent. */
657 if (*cp
== 'e' || *cp
== 'E') {
658 bool negative_exponent
= false;
664 } else if (*cp
== '-') {
665 negative_exponent
= true;
670 json_error(p
, "exponent must contain at least one digit");
676 if (exponent
>= INT_MAX
/ 10) {
677 json_error(p
, "exponent outside valid range");
680 exponent
= exponent
* 10 + (*cp
- '0');
682 } while (isdigit(*cp
));
684 if (negative_exponent
) {
692 json_error(p
, "syntax error in number");
696 /* Figure out number.
698 * We suppress negative zeros as a matter of policy. */
700 struct json_token token
;
701 token
.type
= T_INTEGER
;
703 json_parser_input(p
, &token
);
708 while (pow10
> 0 && significand
< ULLONG_MAX
/ 10) {
713 while (pow10
< 0 && significand
% 10 == 0) {
719 && significand
<= (negative
720 ? (unsigned long long int) LLONG_MAX
+ 1
722 struct json_token token
;
723 token
.type
= T_INTEGER
;
724 token
.u
.integer
= negative
? -significand
: significand
;
725 json_parser_input(p
, &token
);
730 if (pow10
+ sig_digits
<= DBL_MAX_10_EXP
) {
731 struct json_token token
;
733 token
.u
.real
= significand
* pow(10.0, pow10
);
734 if (token
.u
.real
<= DBL_MAX
) {
735 if (negative
&& token
.u
.real
) {
736 token
.u
.real
= -token
.u
.real
;
738 json_parser_input(p
, &token
);
742 json_error(p
, "number outside valid range");
746 json_lex_4hex(struct json_parser
*p
, const char *cp
, int *valuep
)
751 for (i
= 0; i
< 4; i
++) {
752 unsigned char c
= *cp
++;
754 json_error(p
, "malformed \\u escape");
757 value
= (value
<< 4) | hexit_value(c
);
760 json_error(p
, "null bytes not supported in quoted strings");
768 json_lex_unicode(struct json_parser
*p
, const char *cp
, struct ds
*s
)
772 if (!json_lex_4hex(p
, cp
, &c0
)) {
776 if (!uc_is_leading_surrogate(c0
)) {
781 if (*cp
++ != '\\' || *cp
++ != 'u') {
782 json_error(p
, "malformed escaped surrogate pair");
786 if (!json_lex_4hex(p
, cp
, &c1
)) {
790 if (!uc_is_trailing_surrogate(c1
)) {
791 json_error(p
, "second half of escaped surrogate pair is not "
792 "trailing surrogate");
796 ds_put_utf8(s
, utf16_decode_surrogate_pair(c0
, c1
));
801 json_lex_string(struct json_parser
*p
)
803 struct json_token token
;
807 cp
= ds_cstr(&p
->buffer
);
808 if (!strchr(cp
, '\\')) {
809 token
.type
= T_STRING
;
811 json_parser_input(p
, &token
);
816 ds_reserve(&s
, strlen(cp
));
817 while (*cp
!= '\0') {
819 ds_put_char(&s
, *cp
++);
825 case '"': case '\\': case '/':
826 ds_put_char(&s
, cp
[-1]);
830 ds_put_char(&s
, '\b');
834 ds_put_char(&s
, '\f');
838 ds_put_char(&s
, '\n');
842 ds_put_char(&s
, '\r');
846 ds_put_char(&s
, '\t');
850 cp
= json_lex_unicode(p
, cp
, &s
);
857 json_error(p
, "bad escape \\%c", cp
[-1]);
862 token
.type
= T_STRING
;
863 token
.u
.string
= ds_cstr(&s
);
864 json_parser_input(p
, &token
);
872 json_lex_input(struct json_parser
*p
, int c
)
874 struct json_token token
;
876 switch (p
->lex_state
) {
879 case ' ': case '\t': case '\n': case '\r':
883 case 'a': case 'b': case 'c': case 'd': case 'e':
884 case 'f': case 'g': case 'h': case 'i': case 'j':
885 case 'k': case 'l': case 'm': case 'n': case 'o':
886 case 'p': case 'q': case 'r': case 's': case 't':
887 case 'u': case 'v': case 'w': case 'x': case 'y':
889 p
->lex_state
= JSON_LEX_KEYWORD
;
892 case '[': case '{': case ']': case '}': case ':': case ',':
894 json_parser_input(p
, &token
);
898 case '0': case '1': case '2': case '3': case '4':
899 case '5': case '6': case '7': case '8': case '9':
900 p
->lex_state
= JSON_LEX_NUMBER
;
904 p
->lex_state
= JSON_LEX_STRING
;
909 json_error(p
, "invalid character '%c'", c
);
911 json_error(p
, "invalid character U+%04x", c
);
917 case JSON_LEX_KEYWORD
:
918 if (!isalpha((unsigned char) c
)) {
924 case JSON_LEX_NUMBER
:
925 if (!strchr(".0123456789eE-+", c
)) {
931 case JSON_LEX_STRING
:
933 p
->lex_state
= JSON_LEX_ESCAPE
;
934 } else if (c
== '"') {
937 } else if (c
< 0x20) {
938 json_error(p
, "U+%04X must be escaped in quoted string", c
);
943 case JSON_LEX_ESCAPE
:
944 p
->lex_state
= JSON_LEX_STRING
;
950 ds_put_char(&p
->buffer
, c
);
956 /* Parses 'string' as a JSON object or array and returns a newly allocated
957 * 'struct json'. The caller must free the returned structure with
958 * json_destroy() when it is no longer needed.
960 * 'string' must be encoded in UTF-8.
962 * If 'string' is valid JSON, then the returned 'struct json' will be either an
963 * object (JSON_OBJECT) or an array (JSON_ARRAY).
965 * If 'string' is not valid JSON, then the returned 'struct json' will be a
966 * string (JSON_STRING) that describes the particular error encountered during
967 * parsing. (This is an acceptable means of error reporting because at its top
968 * level JSON must be either an object or an array; a bare string is not
971 json_from_string(const char *string
)
973 struct json_parser
*p
= json_parser_create(JSPF_TRAILER
);
974 json_parser_feed(p
, string
, strlen(string
));
975 return json_parser_finish(p
);
978 /* Reads the file named 'file_name', parses its contents as a JSON object or
979 * array, and returns a newly allocated 'struct json'. The caller must free
980 * the returned structure with json_destroy() when it is no longer needed.
982 * The file must be encoded in UTF-8.
984 * See json_from_string() for return value semantics.
987 json_from_file(const char *file_name
)
989 struct json_parser
*p
;
994 stream
= fopen(file_name
, "r");
996 return json_string_create_nocopy(
997 xasprintf("error opening \"%s\": %s", file_name
, strerror(errno
)));
1000 /* Read and parse file. */
1001 p
= json_parser_create(JSPF_TRAILER
);
1003 char buffer
[BUFSIZ
];
1006 n
= fread(buffer
, 1, sizeof buffer
, stream
);
1007 if (!n
|| json_parser_feed(p
, buffer
, n
) != n
) {
1011 json
= json_parser_finish(p
);
1013 /* Close file and check for I/O errors. */
1014 if (ferror(stream
)) {
1016 json
= json_string_create_nocopy(
1017 xasprintf("error reading \"%s\": %s", file_name
, strerror(errno
)));
1024 struct json_parser
*
1025 json_parser_create(int flags
)
1027 struct json_parser
*p
= xzalloc(sizeof *p
);
1033 json_parser_feed(struct json_parser
*p
, const char *input
, size_t n
)
1036 for (i
= 0; !p
->done
&& i
< n
; ) {
1037 if (json_lex_input(p
, input
[i
])) {
1045 json_parser_is_done(const struct json_parser
*p
)
1051 json_parser_finish(struct json_parser
*p
)
1055 switch (p
->lex_state
) {
1056 case JSON_LEX_START
:
1059 case JSON_LEX_STRING
:
1060 case JSON_LEX_ESCAPE
:
1061 json_error(p
, "unexpected end of input in quoted string");
1064 case JSON_LEX_NUMBER
:
1065 case JSON_LEX_KEYWORD
:
1066 json_lex_input(p
, ' ');
1070 if (p
->parse_state
== JSON_PARSE_START
) {
1071 json_error(p
, "empty input stream");
1072 } else if (p
->parse_state
!= JSON_PARSE_END
) {
1073 json_error(p
, "unexpected end of input");
1077 assert(p
->height
== 1);
1078 assert(p
->stack
[0].json
!= NULL
);
1079 json
= p
->stack
[--p
->height
].json
;
1081 json
= json_string_create_nocopy(p
->error
);
1085 json_parser_abort(p
);
1091 json_parser_abort(struct json_parser
*p
)
1094 ds_destroy(&p
->buffer
);
1096 json_destroy(p
->stack
[0].json
);
1099 free(p
->member_name
);
1105 static struct json_parser_node
*
1106 json_parser_top(struct json_parser
*p
)
1108 return &p
->stack
[p
->height
- 1];
1112 json_parser_put_value(struct json_parser
*p
, struct json
*value
)
1114 struct json_parser_node
*node
= json_parser_top(p
);
1115 if (node
->json
->type
== JSON_OBJECT
) {
1116 json_object_put(node
->json
, p
->member_name
, value
);
1117 free(p
->member_name
);
1118 p
->member_name
= NULL
;
1119 } else if (node
->json
->type
== JSON_ARRAY
) {
1120 json_array_add(node
->json
, value
);
1126 static struct json_parser_node
*
1127 json_parser_push(struct json_parser
*p
,
1128 struct json
*new_json
, enum json_parse_state new_state
)
1130 if (p
->height
< JSON_MAX_HEIGHT
) {
1131 struct json_parser_node
*node
;
1133 if (p
->height
>= p
->allocated_height
) {
1134 p
->stack
= x2nrealloc(p
->stack
, &p
->allocated_height
,
1138 if (p
->height
> 0) {
1139 json_parser_put_value(p
, new_json
);
1142 node
= &p
->stack
[p
->height
++];
1143 node
->json
= new_json
;
1144 p
->parse_state
= new_state
;
1147 json_error(p
, "input exceeds maximum nesting depth %d",
1154 json_parser_push_object(struct json_parser
*p
)
1156 json_parser_push(p
, json_object_create(), JSON_PARSE_OBJECT_INIT
);
1160 json_parser_push_array(struct json_parser
*p
)
1162 json_parser_push(p
, json_array_create_empty(), JSON_PARSE_ARRAY_INIT
);
1166 json_parse_value(struct json_parser
*p
, struct json_token
*token
,
1167 enum json_parse_state next_state
)
1171 switch (token
->type
) {
1173 value
= json_boolean_create(false);
1177 value
= json_null_create();
1181 value
= json_boolean_create(true);
1185 json_parser_push_object(p
);
1189 json_parser_push_array(p
);
1193 value
= json_integer_create(token
->u
.integer
);
1197 value
= json_real_create(token
->u
.real
);
1201 value
= json_string_create(token
->u
.string
);
1210 json_error(p
, "syntax error expecting value");
1214 json_parser_put_value(p
, value
);
1215 p
->parse_state
= next_state
;
1219 json_parser_pop(struct json_parser
*p
)
1221 struct json_parser_node
*node
;
1223 /* Conserve memory. */
1224 node
= json_parser_top(p
);
1225 if (node
->json
->type
== JSON_ARRAY
) {
1226 json_array_trim(node
->json
);
1229 /* Pop off the top-of-stack. */
1230 if (p
->height
== 1) {
1231 p
->parse_state
= JSON_PARSE_END
;
1232 if (!(p
->flags
& JSPF_TRAILER
)) {
1237 node
= json_parser_top(p
);
1238 if (node
->json
->type
== JSON_ARRAY
) {
1239 p
->parse_state
= JSON_PARSE_ARRAY_NEXT
;
1240 } else if (node
->json
->type
== JSON_OBJECT
) {
1241 p
->parse_state
= JSON_PARSE_OBJECT_NEXT
;
1249 json_parser_input(struct json_parser
*p
, struct json_token
*token
)
1251 switch (p
->parse_state
) {
1252 case JSON_PARSE_START
:
1253 if (token
->type
== '{') {
1254 json_parser_push_object(p
);
1255 } else if (token
->type
== '[') {
1256 json_parser_push_array(p
);
1258 json_error(p
, "syntax error at beginning of input");
1262 case JSON_PARSE_END
:
1263 json_error(p
, "trailing garbage at end of input");
1266 case JSON_PARSE_OBJECT_INIT
:
1267 if (token
->type
== '}') {
1272 case JSON_PARSE_OBJECT_NAME
:
1273 if (token
->type
== T_STRING
) {
1274 p
->member_name
= xstrdup(token
->u
.string
);
1275 p
->parse_state
= JSON_PARSE_OBJECT_COLON
;
1277 json_error(p
, "syntax error parsing object expecting string");
1281 case JSON_PARSE_OBJECT_COLON
:
1282 if (token
->type
== ':') {
1283 p
->parse_state
= JSON_PARSE_OBJECT_VALUE
;
1285 json_error(p
, "syntax error parsing object expecting ':'");
1289 case JSON_PARSE_OBJECT_VALUE
:
1290 json_parse_value(p
, token
, JSON_PARSE_OBJECT_NEXT
);
1293 case JSON_PARSE_OBJECT_NEXT
:
1294 if (token
->type
== ',') {
1295 p
->parse_state
= JSON_PARSE_OBJECT_NAME
;
1296 } else if (token
->type
== '}') {
1299 json_error(p
, "syntax error expecting '}' or ','");
1303 case JSON_PARSE_ARRAY_INIT
:
1304 if (token
->type
== ']') {
1309 case JSON_PARSE_ARRAY_VALUE
:
1310 json_parse_value(p
, token
, JSON_PARSE_ARRAY_NEXT
);
1313 case JSON_PARSE_ARRAY_NEXT
:
1314 if (token
->type
== ',') {
1315 p
->parse_state
= JSON_PARSE_ARRAY_VALUE
;
1316 } else if (token
->type
== ']') {
1319 json_error(p
, "syntax error expecting ']' or ','");
1327 p
->lex_state
= JSON_LEX_START
;
1328 ds_clear(&p
->buffer
);
1331 static struct json
*
1332 json_create(enum json_type type
)
1334 struct json
*json
= xmalloc(sizeof *json
);
1340 json_error(struct json_parser
*p
, const char *format
, ...)
1345 va_start(args
, format
);
1346 p
->error
= xvasprintf(format
, args
);
1353 #define SPACES_PER_LEVEL 2
1355 struct json_serializer
{
1361 static void json_to_ds(const struct json
*, struct json_serializer
*);
1362 static void json_object_to_ds(const struct shash
*object
,
1363 struct json_serializer
*);
1364 static void json_array_to_ds(const struct json_array
*,
1365 struct json_serializer
*);
1366 static void json_string_to_ds(const char *string
, struct ds
*);
1368 /* Converts 'json' to a string in JSON format, encoded in UTF-8, and returns
1369 * that string. The caller is responsible for freeing the returned string,
1370 * with free(), when it is no longer needed.
1372 * If 'flags' contains JSSF_PRETTY, the output is pretty-printed with each
1373 * nesting level introducing an additional indentation. Otherwise, the
1374 * returned string does not contain any new-line characters.
1376 * If 'flags' contains JSSF_SORT, members of objects in the output are sorted
1377 * in bytewise lexicographic order for reproducibility. Otherwise, members of
1378 * objects are output in an indeterminate order.
1380 * The returned string is valid JSON only if 'json' represents an array or an
1381 * object, since a bare literal does not satisfy the JSON grammar. */
1383 json_to_string(const struct json
*json
, int flags
)
1385 struct json_serializer s
;
1389 json_to_ds(json
, &s
);
1390 return ds_steal_cstr(&s
.ds
);
1394 json_to_ds(const struct json
*json
, struct json_serializer
*s
)
1396 struct ds
*ds
= &s
->ds
;
1398 switch (json
->type
) {
1400 ds_put_cstr(ds
, "null");
1404 ds_put_cstr(ds
, "false");
1408 ds_put_cstr(ds
, "true");
1412 json_object_to_ds(json
->u
.object
, s
);
1416 json_array_to_ds(&json
->u
.array
, s
);
1420 ds_put_format(ds
, "%lld", json
->u
.integer
);
1424 ds_put_format(ds
, "%.*g", DBL_DIG
, json
->u
.real
);
1428 json_string_to_ds(json
->u
.string
, ds
);
1438 indent_line(struct json_serializer
*s
)
1440 if (s
->flags
& JSSF_PRETTY
) {
1441 ds_put_char(&s
->ds
, '\n');
1442 ds_put_char_multiple(&s
->ds
, ' ', SPACES_PER_LEVEL
* s
->depth
);
1447 json_object_member_to_ds(size_t i
, const struct shash_node
*node
,
1448 struct json_serializer
*s
)
1450 struct ds
*ds
= &s
->ds
;
1453 ds_put_char(ds
, ',');
1457 json_string_to_ds(node
->name
, ds
);
1458 ds_put_char(ds
, ':');
1459 if (s
->flags
& JSSF_PRETTY
) {
1460 ds_put_char(ds
, ' ');
1462 json_to_ds(node
->data
, s
);
1466 json_object_to_ds(const struct shash
*object
, struct json_serializer
*s
)
1468 struct ds
*ds
= &s
->ds
;
1470 ds_put_char(ds
, '{');
1475 if (s
->flags
& JSSF_SORT
) {
1476 const struct shash_node
**nodes
;
1479 nodes
= shash_sort(object
);
1480 n
= shash_count(object
);
1481 for (i
= 0; i
< n
; i
++) {
1482 json_object_member_to_ds(i
, nodes
[i
], s
);
1486 struct shash_node
*node
;
1490 SHASH_FOR_EACH (node
, object
) {
1491 json_object_member_to_ds(i
++, node
, s
);
1495 ds_put_char(ds
, '}');
1500 json_array_to_ds(const struct json_array
*array
, struct json_serializer
*s
)
1502 struct ds
*ds
= &s
->ds
;
1505 ds_put_char(ds
, '[');
1511 for (i
= 0; i
< array
->n
; i
++) {
1513 ds_put_char(ds
, ',');
1516 json_to_ds(array
->elems
[i
], s
);
1521 ds_put_char(ds
, ']');
1525 json_string_to_ds(const char *string
, struct ds
*ds
)
1529 ds_put_char(ds
, '"');
1530 while ((c
= *string
++) != '\0') {
1533 ds_put_cstr(ds
, "\\\"");
1537 ds_put_cstr(ds
, "\\\\");
1541 ds_put_cstr(ds
, "\\b");
1545 ds_put_cstr(ds
, "\\f");
1549 ds_put_cstr(ds
, "\\n");
1553 ds_put_cstr(ds
, "\\r");
1557 ds_put_cstr(ds
, "\\t");
1564 ds_put_format(ds
, "\\u%04x", c
);
1569 ds_put_char(ds
, '"');