2 * Copyright (c) 2009-2012, 2014-2017 Nicira, Inc.
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.
19 #include "openvswitch/json.h"
27 #include "openvswitch/dynamic-string.h"
29 #include "openvswitch/shash.h"
34 /* The type of a JSON token. */
35 enum json_token_type
{
41 T_NAME_SEPARATOR
= ':',
42 T_VALUE_SEPARATOR
= ',',
43 T_FALSE
= UCHAR_MAX
+ 1,
53 * RFC 4627 doesn't define a lexical structure for JSON but I believe this to
54 * be compliant with the standard.
57 enum json_token_type type
;
60 long long int integer
;
66 JSON_LEX_START
, /* Not inside a token. */
67 JSON_LEX_NUMBER
, /* Reading a number. */
68 JSON_LEX_KEYWORD
, /* Reading a keyword. */
69 JSON_LEX_STRING
, /* Reading a quoted string. */
70 JSON_LEX_ESCAPE
/* In a quoted string just after a "\". */
73 enum json_parse_state
{
74 JSON_PARSE_START
, /* Beginning of input. */
75 JSON_PARSE_END
, /* End of input. */
78 JSON_PARSE_OBJECT_INIT
, /* Expecting '}' or an object name. */
79 JSON_PARSE_OBJECT_NAME
, /* Expecting an object name. */
80 JSON_PARSE_OBJECT_COLON
, /* Expecting ':'. */
81 JSON_PARSE_OBJECT_VALUE
, /* Expecting an object value. */
82 JSON_PARSE_OBJECT_NEXT
, /* Expecting ',' or '}'. */
85 JSON_PARSE_ARRAY_INIT
, /* Expecting ']' or a value. */
86 JSON_PARSE_ARRAY_VALUE
, /* Expecting a value. */
87 JSON_PARSE_ARRAY_NEXT
/* Expecting ',' or ']'. */
90 struct json_parser_node
{
98 /* Lexical analysis. */
99 enum json_lex_state lex_state
;
100 struct ds buffer
; /* Buffer for accumulating token text. */
106 enum json_parse_state parse_state
;
107 #define JSON_MAX_HEIGHT 1000
108 struct json_parser_node
*stack
;
109 size_t height
, allocated_height
;
114 char *error
; /* Error message, if any, null if none yet. */
117 static struct json
*json_create(enum json_type type
);
118 static void json_parser_input(struct json_parser
*, struct json_token
*);
120 static void json_error(struct json_parser
*p
, const char *format
, ...)
121 OVS_PRINTF_FORMAT(2, 3);
124 json_type_to_string(enum json_type type
)
155 /* Functions for manipulating struct json. */
158 json_null_create(void)
160 return json_create(JSON_NULL
);
164 json_boolean_create(bool b
)
166 return json_create(b
? JSON_TRUE
: JSON_FALSE
);
170 json_string_create_nocopy(char *s
)
172 struct json
*json
= json_create(JSON_STRING
);
178 json_string_create(const char *s
)
180 return json_string_create_nocopy(xstrdup(s
));
184 json_array_create_empty(void)
186 struct json
*json
= json_create(JSON_ARRAY
);
187 json
->array
.elems
= NULL
;
189 json
->array
.n_allocated
= 0;
194 json_array_add(struct json
*array_
, struct json
*element
)
196 struct json_array
*array
= json_array(array_
);
197 if (array
->n
>= array
->n_allocated
) {
198 array
->elems
= x2nrealloc(array
->elems
, &array
->n_allocated
,
199 sizeof *array
->elems
);
201 array
->elems
[array
->n
++] = element
;
205 json_array_trim(struct json
*array_
)
207 struct json_array
*array
= json_array(array_
);
208 if (array
->n
< array
->n_allocated
){
209 array
->n_allocated
= array
->n
;
210 array
->elems
= xrealloc(array
->elems
, array
->n
* sizeof *array
->elems
);
215 json_array_create(struct json
**elements
, size_t n
)
217 struct json
*json
= json_create(JSON_ARRAY
);
218 json
->array
.elems
= elements
;
220 json
->array
.n_allocated
= n
;
225 json_array_create_1(struct json
*elem0
)
227 struct json
**elems
= xmalloc(sizeof *elems
);
229 return json_array_create(elems
, 1);
233 json_array_create_2(struct json
*elem0
, struct json
*elem1
)
235 struct json
**elems
= xmalloc(2 * sizeof *elems
);
238 return json_array_create(elems
, 2);
242 json_array_create_3(struct json
*elem0
, struct json
*elem1
, struct json
*elem2
)
244 struct json
**elems
= xmalloc(3 * sizeof *elems
);
248 return json_array_create(elems
, 3);
252 json_object_create(void)
254 struct json
*json
= json_create(JSON_OBJECT
);
255 json
->object
= xmalloc(sizeof *json
->object
);
256 shash_init(json
->object
);
261 json_integer_create(long long int integer
)
263 struct json
*json
= json_create(JSON_INTEGER
);
264 json
->integer
= integer
;
269 json_real_create(double real
)
271 struct json
*json
= json_create(JSON_REAL
);
277 json_object_put(struct json
*json
, const char *name
, struct json
*value
)
279 json_destroy(shash_replace(json
->object
, name
, value
));
283 json_object_put_nocopy(struct json
*json
, char *name
, struct json
*value
)
285 json_destroy(shash_replace_nocopy(json
->object
, name
, value
));
289 json_object_put_string(struct json
*json
, const char *name
, const char *value
)
291 json_object_put(json
, name
, json_string_create(value
));
294 void OVS_PRINTF_FORMAT(3, 4)
295 json_object_put_format(struct json
*json
,
296 const char *name
, const char *format
, ...)
299 va_start(args
, format
);
300 json_object_put(json
, name
,
301 json_string_create_nocopy(xvasprintf(format
, args
)));
306 json_string(const struct json
*json
)
308 ovs_assert(json
->type
== JSON_STRING
);
313 json_array(const struct json
*json
)
315 ovs_assert(json
->type
== JSON_ARRAY
);
316 return CONST_CAST(struct json_array
*, &json
->array
);
320 json_object(const struct json
*json
)
322 ovs_assert(json
->type
== JSON_OBJECT
);
323 return CONST_CAST(struct shash
*, json
->object
);
327 json_boolean(const struct json
*json
)
329 ovs_assert(json
->type
== JSON_TRUE
|| json
->type
== JSON_FALSE
);
330 return json
->type
== JSON_TRUE
;
334 json_real(const struct json
*json
)
336 ovs_assert(json
->type
== JSON_REAL
|| json
->type
== JSON_INTEGER
);
337 return json
->type
== JSON_REAL
? json
->real
: json
->integer
;
341 json_integer(const struct json
*json
)
343 ovs_assert(json
->type
== JSON_INTEGER
);
344 return json
->integer
;
347 static void json_destroy_object(struct shash
*object
);
348 static void json_destroy_array(struct json_array
*array
);
350 /* Frees 'json' and everything it points to, recursively. */
352 json_destroy(struct json
*json
)
354 if (json
&& !--json
->count
) {
355 switch (json
->type
) {
357 json_destroy_object(json
->object
);
361 json_destroy_array(&json
->array
);
383 json_destroy_object(struct shash
*object
)
385 struct shash_node
*node
, *next
;
387 SHASH_FOR_EACH_SAFE (node
, next
, object
) {
388 struct json
*value
= node
->data
;
391 shash_delete(object
, node
);
393 shash_destroy(object
);
398 json_destroy_array(struct json_array
*array
)
402 for (i
= 0; i
< array
->n
; i
++) {
403 json_destroy(array
->elems
[i
]);
408 static struct json
*json_clone_object(const struct shash
*object
);
409 static struct json
*json_clone_array(const struct json_array
*array
);
411 /* Returns a deep copy of 'json'. */
413 json_deep_clone(const struct json
*json
)
415 switch (json
->type
) {
417 return json_clone_object(json
->object
);
420 return json_clone_array(&json
->array
);
423 return json_string_create(json
->string
);
428 return json_create(json
->type
);
431 return json_integer_create(json
->integer
);
434 return json_real_create(json
->real
);
442 /* Returns 'json', with the reference count incremented. */
444 json_clone(const struct json
*json_
)
446 struct json
*json
= CONST_CAST(struct json
*, json_
);
452 json_nullable_clone(const struct json
*json
)
454 return json
? json_clone(json
) : NULL
;
458 json_clone_object(const struct shash
*object
)
460 struct shash_node
*node
;
463 json
= json_object_create();
464 SHASH_FOR_EACH (node
, object
) {
465 struct json
*value
= node
->data
;
466 json_object_put(json
, node
->name
, json_clone(value
));
472 json_clone_array(const struct json_array
*array
)
477 elems
= xmalloc(array
->n
* sizeof *elems
);
478 for (i
= 0; i
< array
->n
; i
++) {
479 elems
[i
] = json_clone(array
->elems
[i
]);
481 return json_array_create(elems
, array
->n
);
485 json_hash_object(const struct shash
*object
, size_t basis
)
487 const struct shash_node
**nodes
;
490 nodes
= shash_sort(object
);
491 n
= shash_count(object
);
492 for (i
= 0; i
< n
; i
++) {
493 const struct shash_node
*node
= nodes
[i
];
494 basis
= hash_string(node
->name
, basis
);
495 basis
= json_hash(node
->data
, basis
);
502 json_hash_array(const struct json_array
*array
, size_t basis
)
506 basis
= hash_int(array
->n
, basis
);
507 for (i
= 0; i
< array
->n
; i
++) {
508 basis
= json_hash(array
->elems
[i
], basis
);
514 json_hash(const struct json
*json
, size_t basis
)
516 switch (json
->type
) {
518 return json_hash_object(json
->object
, basis
);
521 return json_hash_array(&json
->array
, basis
);
524 return hash_string(json
->string
, basis
);
529 return hash_int(json
->type
<< 8, basis
);
532 return hash_int(json
->integer
, basis
);
535 return hash_double(json
->real
, basis
);
544 json_equal_object(const struct shash
*a
, const struct shash
*b
)
546 struct shash_node
*a_node
;
548 if (shash_count(a
) != shash_count(b
)) {
552 SHASH_FOR_EACH (a_node
, a
) {
553 struct shash_node
*b_node
= shash_find(b
, a_node
->name
);
554 if (!b_node
|| !json_equal(a_node
->data
, b_node
->data
)) {
563 json_equal_array(const struct json_array
*a
, const struct json_array
*b
)
571 for (i
= 0; i
< a
->n
; i
++) {
572 if (!json_equal(a
->elems
[i
], b
->elems
[i
])) {
581 json_equal(const struct json
*a
, const struct json
*b
)
585 } else if (!a
|| !b
) {
587 } else if (a
->type
!= b
->type
) {
593 return json_equal_object(a
->object
, b
->object
);
596 return json_equal_array(&a
->array
, &b
->array
);
599 return !strcmp(a
->string
, b
->string
);
607 return a
->integer
== b
->integer
;
610 return a
->real
== b
->real
;
618 /* Lexical analysis. */
621 json_lex_keyword(struct json_parser
*p
)
623 struct json_token token
;
626 s
= ds_cstr(&p
->buffer
);
627 if (!strcmp(s
, "false")) {
628 token
.type
= T_FALSE
;
629 } else if (!strcmp(s
, "true")) {
631 } else if (!strcmp(s
, "null")) {
634 json_error(p
, "invalid keyword '%s'", s
);
637 json_parser_input(p
, &token
);
641 json_lex_number(struct json_parser
*p
)
643 const char *cp
= ds_cstr(&p
->buffer
);
644 unsigned long long int significand
= 0;
645 struct json_token token
;
646 bool imprecise
= false;
647 bool negative
= false;
650 /* Leading minus sign. */
656 /* At least one integer digit, but 0 may not be used as a leading digit for
657 * a longer number. */
661 if (isdigit((unsigned char) *cp
)) {
662 json_error(p
, "leading zeros not allowed");
665 } else if (isdigit((unsigned char) *cp
)) {
667 if (significand
<= ULLONG_MAX
/ 10) {
668 significand
= significand
* 10 + (*cp
- '0');
676 } while (isdigit((unsigned char) *cp
));
678 json_error(p
, "'-' must be followed by digit");
682 /* Optional fraction. */
685 if (!isdigit((unsigned char) *cp
)) {
686 json_error(p
, "decimal point must be followed by digit");
690 if (significand
<= ULLONG_MAX
/ 10) {
691 significand
= significand
* 10 + (*cp
- '0');
693 } else if (*cp
!= '0') {
697 } while (isdigit((unsigned char) *cp
));
700 /* Optional exponent. */
701 if (*cp
== 'e' || *cp
== 'E') {
702 bool negative_exponent
= false;
708 } else if (*cp
== '-') {
709 negative_exponent
= true;
713 if (!isdigit((unsigned char) *cp
)) {
714 json_error(p
, "exponent must contain at least one digit");
720 if (exponent
>= INT_MAX
/ 10) {
723 exponent
= exponent
* 10 + (*cp
- '0');
725 } while (isdigit((unsigned char) *cp
));
727 if (negative_exponent
) {
728 if (pow10
< INT_MIN
+ exponent
) {
733 if (pow10
> INT_MAX
- exponent
) {
741 json_error(p
, "syntax error in number");
745 /* Figure out number.
747 * We suppress negative zeros as a matter of policy. */
749 token
.type
= T_INTEGER
;
751 json_parser_input(p
, &token
);
756 while (pow10
> 0 && significand
< ULLONG_MAX
/ 10) {
760 while (pow10
< 0 && significand
% 10 == 0) {
765 && significand
<= (negative
766 ? (unsigned long long int) LLONG_MAX
+ 1
768 token
.type
= T_INTEGER
;
769 token
.integer
= negative
? -significand
: significand
;
770 json_parser_input(p
, &token
);
776 if (!str_to_double(ds_cstr(&p
->buffer
), &token
.real
)) {
777 json_error(p
, "number outside valid range");
780 /* Suppress negative zero. */
781 if (token
.real
== 0) {
784 json_parser_input(p
, &token
);
788 json_error(p
, "exponent outside valid range");
792 json_lex_4hex(const char *cp
, const char *end
, int *valuep
)
798 return "quoted string ends within \\u escape";
801 value
= hexits_value(cp
, 4, &ok
);
803 return "malformed \\u escape";
806 return "null bytes not supported in quoted strings";
813 json_lex_unicode(const char *cp
, const char *end
, struct ds
*out
)
818 error
= json_lex_4hex(cp
, end
, &c0
);
821 ds_put_cstr(out
, error
);
825 if (!uc_is_leading_surrogate(c0
)) {
826 ds_put_utf8(out
, c0
);
830 if (cp
+ 2 > end
|| *cp
++ != '\\' || *cp
++ != 'u') {
832 ds_put_cstr(out
, "malformed escaped surrogate pair");
836 error
= json_lex_4hex(cp
, end
, &c1
);
839 ds_put_cstr(out
, error
);
843 if (!uc_is_trailing_surrogate(c1
)) {
845 ds_put_cstr(out
, "second half of escaped surrogate pair is not "
846 "trailing surrogate");
850 ds_put_utf8(out
, utf16_decode_surrogate_pair(c0
, c1
));
855 json_string_unescape(const char *in
, size_t in_len
, char **outp
)
857 const char *end
= in
+ in_len
;
862 ds_reserve(&out
, in_len
);
866 ds_put_cstr(&out
, "quoted string may not include unescaped \"");
870 ds_put_char(&out
, *in
++);
876 /* The JSON parser will never trigger this message, because its
877 * lexer will never pass in a string that ends in a single
878 * backslash, but json_string_unescape() has other callers that
879 * are not as careful.*/
881 ds_put_cstr(&out
, "quoted string may not end with backslash");
885 case '"': case '\\': case '/':
886 ds_put_char(&out
, in
[-1]);
890 ds_put_char(&out
, '\b');
894 ds_put_char(&out
, '\f');
898 ds_put_char(&out
, '\n');
902 ds_put_char(&out
, '\r');
906 ds_put_char(&out
, '\t');
910 in
= json_lex_unicode(in
, end
, &out
);
918 ds_put_format(&out
, "bad escape \\%c", in
[-1]);
925 *outp
= ds_cstr(&out
);
930 json_string_escape(const char *in
, struct ds
*out
)
934 .string
= CONST_CAST(char *, in
),
936 json_to_ds(&json
, 0, out
);
940 json_parser_input_string(struct json_parser
*p
, const char *s
)
942 struct json_token token
;
944 token
.type
= T_STRING
;
946 json_parser_input(p
, &token
);
950 json_lex_string(struct json_parser
*p
)
952 const char *raw
= ds_cstr(&p
->buffer
);
953 if (!strchr(raw
, '\\')) {
954 json_parser_input_string(p
, raw
);
958 if (json_string_unescape(raw
, strlen(raw
), &cooked
)) {
959 json_parser_input_string(p
, cooked
);
961 json_error(p
, "%s", cooked
);
969 json_lex_input(struct json_parser
*p
, unsigned char c
)
971 struct json_token token
;
973 switch (p
->lex_state
) {
976 case ' ': case '\t': case '\n': case '\r':
980 case 'a': case 'b': case 'c': case 'd': case 'e':
981 case 'f': case 'g': case 'h': case 'i': case 'j':
982 case 'k': case 'l': case 'm': case 'n': case 'o':
983 case 'p': case 'q': case 'r': case 's': case 't':
984 case 'u': case 'v': case 'w': case 'x': case 'y':
986 p
->lex_state
= JSON_LEX_KEYWORD
;
989 case '[': case '{': case ']': case '}': case ':': case ',':
991 json_parser_input(p
, &token
);
995 case '0': case '1': case '2': case '3': case '4':
996 case '5': case '6': case '7': case '8': case '9':
997 p
->lex_state
= JSON_LEX_NUMBER
;
1001 p
->lex_state
= JSON_LEX_STRING
;
1006 json_error(p
, "invalid character '%c'", c
);
1008 json_error(p
, "invalid character U+%04x", c
);
1014 case JSON_LEX_KEYWORD
:
1015 if (!isalpha((unsigned char) c
)) {
1016 json_lex_keyword(p
);
1021 case JSON_LEX_NUMBER
:
1022 if (!strchr(".0123456789eE-+", c
)) {
1028 case JSON_LEX_STRING
:
1030 p
->lex_state
= JSON_LEX_ESCAPE
;
1031 } else if (c
== '"') {
1034 } else if (c
< 0x20) {
1035 json_error(p
, "U+%04X must be escaped in quoted string", c
);
1040 case JSON_LEX_ESCAPE
:
1041 p
->lex_state
= JSON_LEX_STRING
;
1047 ds_put_char(&p
->buffer
, c
);
1053 /* Parses 'string' as a JSON object or array and returns a newly allocated
1054 * 'struct json'. The caller must free the returned structure with
1055 * json_destroy() when it is no longer needed.
1057 * 'string' must be encoded in UTF-8.
1059 * If 'string' is valid JSON, then the returned 'struct json' will be either an
1060 * object (JSON_OBJECT) or an array (JSON_ARRAY).
1062 * If 'string' is not valid JSON, then the returned 'struct json' will be a
1063 * string (JSON_STRING) that describes the particular error encountered during
1064 * parsing. (This is an acceptable means of error reporting because at its top
1065 * level JSON must be either an object or an array; a bare string is not
1068 json_from_string(const char *string
)
1070 struct json_parser
*p
= json_parser_create(JSPF_TRAILER
);
1071 json_parser_feed(p
, string
, strlen(string
));
1072 return json_parser_finish(p
);
1075 /* Reads the file named 'file_name', parses its contents as a JSON object or
1076 * array, and returns a newly allocated 'struct json'. The caller must free
1077 * the returned structure with json_destroy() when it is no longer needed.
1079 * The file must be encoded in UTF-8.
1081 * See json_from_string() for return value semantics.
1084 json_from_file(const char *file_name
)
1089 stream
= fopen(file_name
, "r");
1091 return json_string_create_nocopy(
1092 xasprintf("error opening \"%s\": %s", file_name
,
1093 ovs_strerror(errno
)));
1095 json
= json_from_stream(stream
);
1101 /* Parses the contents of 'stream' as a JSON object or array, and returns a
1102 * newly allocated 'struct json'. The caller must free the returned structure
1103 * with json_destroy() when it is no longer needed.
1105 * The file must be encoded in UTF-8.
1107 * See json_from_string() for return value semantics.
1110 json_from_stream(FILE *stream
)
1112 struct json_parser
*p
;
1115 p
= json_parser_create(JSPF_TRAILER
);
1117 char buffer
[BUFSIZ
];
1120 n
= fread(buffer
, 1, sizeof buffer
, stream
);
1121 if (!n
|| json_parser_feed(p
, buffer
, n
) != n
) {
1125 json
= json_parser_finish(p
);
1127 if (ferror(stream
)) {
1129 json
= json_string_create_nocopy(
1130 xasprintf("error reading JSON stream: %s", ovs_strerror(errno
)));
1136 struct json_parser
*
1137 json_parser_create(int flags
)
1139 struct json_parser
*p
= xzalloc(sizeof *p
);
1145 json_parser_feed(struct json_parser
*p
, const char *input
, size_t n
)
1148 for (i
= 0; !p
->done
&& i
< n
; ) {
1149 if (json_lex_input(p
, input
[i
])) {
1151 if (input
[i
] == '\n') {
1152 p
->column_number
= 0;
1164 json_parser_is_done(const struct json_parser
*p
)
1170 json_parser_finish(struct json_parser
*p
)
1174 switch (p
->lex_state
) {
1175 case JSON_LEX_START
:
1178 case JSON_LEX_STRING
:
1179 case JSON_LEX_ESCAPE
:
1180 json_error(p
, "unexpected end of input in quoted string");
1183 case JSON_LEX_NUMBER
:
1184 case JSON_LEX_KEYWORD
:
1185 json_lex_input(p
, ' ');
1189 if (p
->parse_state
== JSON_PARSE_START
) {
1190 json_error(p
, "empty input stream");
1191 } else if (p
->parse_state
!= JSON_PARSE_END
) {
1192 json_error(p
, "unexpected end of input");
1196 ovs_assert(p
->height
== 1);
1197 ovs_assert(p
->stack
[0].json
!= NULL
);
1198 json
= p
->stack
[--p
->height
].json
;
1200 json
= json_string_create_nocopy(p
->error
);
1204 json_parser_abort(p
);
1210 json_parser_abort(struct json_parser
*p
)
1213 ds_destroy(&p
->buffer
);
1215 json_destroy(p
->stack
[0].json
);
1218 free(p
->member_name
);
1224 static struct json_parser_node
*
1225 json_parser_top(struct json_parser
*p
)
1227 return &p
->stack
[p
->height
- 1];
1231 json_parser_put_value(struct json_parser
*p
, struct json
*value
)
1233 struct json_parser_node
*node
= json_parser_top(p
);
1234 if (node
->json
->type
== JSON_OBJECT
) {
1235 json_object_put_nocopy(node
->json
, p
->member_name
, value
);
1236 p
->member_name
= NULL
;
1237 } else if (node
->json
->type
== JSON_ARRAY
) {
1238 json_array_add(node
->json
, value
);
1245 json_parser_push(struct json_parser
*p
,
1246 struct json
*new_json
, enum json_parse_state new_state
)
1248 if (p
->height
< JSON_MAX_HEIGHT
) {
1249 struct json_parser_node
*node
;
1251 if (p
->height
>= p
->allocated_height
) {
1252 p
->stack
= x2nrealloc(p
->stack
, &p
->allocated_height
,
1256 if (p
->height
> 0) {
1257 json_parser_put_value(p
, new_json
);
1260 node
= &p
->stack
[p
->height
++];
1261 node
->json
= new_json
;
1262 p
->parse_state
= new_state
;
1264 json_destroy(new_json
);
1265 json_error(p
, "input exceeds maximum nesting depth %d",
1271 json_parser_push_object(struct json_parser
*p
)
1273 json_parser_push(p
, json_object_create(), JSON_PARSE_OBJECT_INIT
);
1277 json_parser_push_array(struct json_parser
*p
)
1279 json_parser_push(p
, json_array_create_empty(), JSON_PARSE_ARRAY_INIT
);
1283 json_parse_value(struct json_parser
*p
, struct json_token
*token
,
1284 enum json_parse_state next_state
)
1288 switch (token
->type
) {
1290 value
= json_boolean_create(false);
1294 value
= json_null_create();
1298 value
= json_boolean_create(true);
1302 json_parser_push_object(p
);
1306 json_parser_push_array(p
);
1310 value
= json_integer_create(token
->integer
);
1314 value
= json_real_create(token
->real
);
1318 value
= json_string_create(token
->string
);
1327 json_error(p
, "syntax error expecting value");
1331 json_parser_put_value(p
, value
);
1332 p
->parse_state
= next_state
;
1336 json_parser_pop(struct json_parser
*p
)
1338 struct json_parser_node
*node
;
1340 /* Conserve memory. */
1341 node
= json_parser_top(p
);
1342 if (node
->json
->type
== JSON_ARRAY
) {
1343 json_array_trim(node
->json
);
1346 /* Pop off the top-of-stack. */
1347 if (p
->height
== 1) {
1348 p
->parse_state
= JSON_PARSE_END
;
1349 if (!(p
->flags
& JSPF_TRAILER
)) {
1354 node
= json_parser_top(p
);
1355 if (node
->json
->type
== JSON_ARRAY
) {
1356 p
->parse_state
= JSON_PARSE_ARRAY_NEXT
;
1357 } else if (node
->json
->type
== JSON_OBJECT
) {
1358 p
->parse_state
= JSON_PARSE_OBJECT_NEXT
;
1366 json_parser_input(struct json_parser
*p
, struct json_token
*token
)
1368 switch (p
->parse_state
) {
1369 case JSON_PARSE_START
:
1370 if (token
->type
== '{') {
1371 json_parser_push_object(p
);
1372 } else if (token
->type
== '[') {
1373 json_parser_push_array(p
);
1375 json_error(p
, "syntax error at beginning of input");
1379 case JSON_PARSE_END
:
1380 json_error(p
, "trailing garbage at end of input");
1383 case JSON_PARSE_OBJECT_INIT
:
1384 if (token
->type
== '}') {
1389 case JSON_PARSE_OBJECT_NAME
:
1390 if (token
->type
== T_STRING
) {
1391 p
->member_name
= xstrdup(token
->string
);
1392 p
->parse_state
= JSON_PARSE_OBJECT_COLON
;
1394 json_error(p
, "syntax error parsing object expecting string");
1398 case JSON_PARSE_OBJECT_COLON
:
1399 if (token
->type
== ':') {
1400 p
->parse_state
= JSON_PARSE_OBJECT_VALUE
;
1402 json_error(p
, "syntax error parsing object expecting ':'");
1406 case JSON_PARSE_OBJECT_VALUE
:
1407 json_parse_value(p
, token
, JSON_PARSE_OBJECT_NEXT
);
1410 case JSON_PARSE_OBJECT_NEXT
:
1411 if (token
->type
== ',') {
1412 p
->parse_state
= JSON_PARSE_OBJECT_NAME
;
1413 } else if (token
->type
== '}') {
1416 json_error(p
, "syntax error expecting '}' or ','");
1420 case JSON_PARSE_ARRAY_INIT
:
1421 if (token
->type
== ']') {
1426 case JSON_PARSE_ARRAY_VALUE
:
1427 json_parse_value(p
, token
, JSON_PARSE_ARRAY_NEXT
);
1430 case JSON_PARSE_ARRAY_NEXT
:
1431 if (token
->type
== ',') {
1432 p
->parse_state
= JSON_PARSE_ARRAY_VALUE
;
1433 } else if (token
->type
== ']') {
1436 json_error(p
, "syntax error expecting ']' or ','");
1444 p
->lex_state
= JSON_LEX_START
;
1445 ds_clear(&p
->buffer
);
1448 static struct json
*
1449 json_create(enum json_type type
)
1451 struct json
*json
= xmalloc(sizeof *json
);
1458 json_error(struct json_parser
*p
, const char *format
, ...)
1465 ds_put_format(&msg
, "line %d, column %d, byte %d: ",
1466 p
->line_number
, p
->column_number
, p
->byte_number
);
1467 va_start(args
, format
);
1468 ds_put_format_valist(&msg
, format
, args
);
1471 p
->error
= ds_steal_cstr(&msg
);
1477 #define SPACES_PER_LEVEL 2
1479 struct json_serializer
{
1485 static void json_serialize(const struct json
*, struct json_serializer
*);
1486 static void json_serialize_object(const struct shash
*object
,
1487 struct json_serializer
*);
1488 static void json_serialize_array(const struct json_array
*,
1489 struct json_serializer
*);
1490 static void json_serialize_string(const char *, struct ds
*);
1492 /* Converts 'json' to a string in JSON format, encoded in UTF-8, and returns
1493 * that string. The caller is responsible for freeing the returned string,
1494 * with free(), when it is no longer needed.
1496 * If 'flags' contains JSSF_PRETTY, the output is pretty-printed with each
1497 * nesting level introducing an additional indentation. Otherwise, the
1498 * returned string does not contain any new-line characters.
1500 * If 'flags' contains JSSF_SORT, members of objects in the output are sorted
1501 * in bytewise lexicographic order for reproducibility. Otherwise, members of
1502 * objects are output in an indeterminate order.
1504 * The returned string is valid JSON only if 'json' represents an array or an
1505 * object, since a bare literal does not satisfy the JSON grammar. */
1507 json_to_string(const struct json
*json
, int flags
)
1512 json_to_ds(json
, flags
, &ds
);
1513 return ds_steal_cstr(&ds
);
1516 /* Same as json_to_string(), but the output is appended to 'ds'. */
1518 json_to_ds(const struct json
*json
, int flags
, struct ds
*ds
)
1520 struct json_serializer s
;
1525 json_serialize(json
, &s
);
1529 json_serialize(const struct json
*json
, struct json_serializer
*s
)
1531 struct ds
*ds
= s
->ds
;
1533 switch (json
->type
) {
1535 ds_put_cstr(ds
, "null");
1539 ds_put_cstr(ds
, "false");
1543 ds_put_cstr(ds
, "true");
1547 json_serialize_object(json
->object
, s
);
1551 json_serialize_array(&json
->array
, s
);
1555 ds_put_format(ds
, "%lld", json
->integer
);
1559 ds_put_format(ds
, "%.*g", DBL_DIG
, json
->real
);
1563 json_serialize_string(json
->string
, ds
);
1573 indent_line(struct json_serializer
*s
)
1575 if (s
->flags
& JSSF_PRETTY
) {
1576 ds_put_char(s
->ds
, '\n');
1577 ds_put_char_multiple(s
->ds
, ' ', SPACES_PER_LEVEL
* s
->depth
);
1582 json_serialize_object_member(size_t i
, const struct shash_node
*node
,
1583 struct json_serializer
*s
)
1585 struct ds
*ds
= s
->ds
;
1588 ds_put_char(ds
, ',');
1592 json_serialize_string(node
->name
, ds
);
1593 ds_put_char(ds
, ':');
1594 if (s
->flags
& JSSF_PRETTY
) {
1595 ds_put_char(ds
, ' ');
1597 json_serialize(node
->data
, s
);
1601 json_serialize_object(const struct shash
*object
, struct json_serializer
*s
)
1603 struct ds
*ds
= s
->ds
;
1605 ds_put_char(ds
, '{');
1610 if (s
->flags
& JSSF_SORT
) {
1611 const struct shash_node
**nodes
;
1614 nodes
= shash_sort(object
);
1615 n
= shash_count(object
);
1616 for (i
= 0; i
< n
; i
++) {
1617 json_serialize_object_member(i
, nodes
[i
], s
);
1621 struct shash_node
*node
;
1625 SHASH_FOR_EACH (node
, object
) {
1626 json_serialize_object_member(i
++, node
, s
);
1630 ds_put_char(ds
, '}');
1635 json_serialize_array(const struct json_array
*array
, struct json_serializer
*s
)
1637 struct ds
*ds
= s
->ds
;
1640 ds_put_char(ds
, '[');
1646 for (i
= 0; i
< array
->n
; i
++) {
1648 ds_put_char(ds
, ',');
1651 json_serialize(array
->elems
[i
], s
);
1656 ds_put_char(ds
, ']');
1659 static const char *chars_escaping
[256] = {
1660 "\\u0000", "\\u0001", "\\u0002", "\\u0003", "\\u0004", "\\u0005", "\\u0006", "\\u0007",
1661 "\\b", "\\t", "\\n", "\\u000b", "\\f", "\\r", "\\u000e", "\\u000f",
1662 "\\u0010", "\\u0011", "\\u0012", "\\u0013", "\\u0014", "\\u0015", "\\u0016", "\\u0017",
1663 "\\u0018", "\\u0019", "\\u001a", "\\u001b", "\\u001c", "\\u001d", "\\u001e", "\\u001f",
1664 " ", "!", "\\\"", "#", "$", "%", "&", "'",
1665 "(", ")", "*", "+", ",", "-", ".", "/",
1666 "0", "1", "2", "3", "4", "5", "6", "7",
1667 "8", "9", ":", ";", "<", "=", ">", "?",
1668 "@", "A", "B", "C", "D", "E", "F", "G",
1669 "H", "I", "J", "K", "L", "M", "N", "O",
1670 "P", "Q", "R", "S", "T", "U", "V", "W",
1671 "X", "Y", "Z", "[", "\\\\", "]", "^", "_",
1672 "`", "a", "b", "c", "d", "e", "f", "g",
1673 "h", "i", "j", "k", "l", "m", "n", "o",
1674 "p", "q", "r", "s", "t", "u", "v", "w",
1675 "x", "y", "z", "{", "|", "}", "~", "\x7f",
1676 "\x80", "\x81", "\x82", "\x83", "\x84", "\x85", "\x86", "\x87",
1677 "\x88", "\x89", "\x8a", "\x8b", "\x8c", "\x8d", "\x8e", "\x8f",
1678 "\x90", "\x91", "\x92", "\x93", "\x94", "\x95", "\x96", "\x97",
1679 "\x98", "\x99", "\x9a", "\x9b", "\x9c", "\x9d", "\x9e", "\x9f",
1680 "\xa0", "\xa1", "\xa2", "\xa3", "\xa4", "\xa5", "\xa6", "\xa7",
1681 "\xa8", "\xa9", "\xaa", "\xab", "\xac", "\xad", "\xae", "\xaf",
1682 "\xb0", "\xb1", "\xb2", "\xb3", "\xb4", "\xb5", "\xb6", "\xb7",
1683 "\xb8", "\xb9", "\xba", "\xbb", "\xbc", "\xbd", "\xbe", "\xbf",
1684 "\xc0", "\xc1", "\xc2", "\xc3", "\xc4", "\xc5", "\xc6", "\xc7",
1685 "\xc8", "\xc9", "\xca", "\xcb", "\xcc", "\xcd", "\xce", "\xcf",
1686 "\xd0", "\xd1", "\xd2", "\xd3", "\xd4", "\xd5", "\xd6", "\xd7",
1687 "\xd8", "\xd9", "\xda", "\xdb", "\xdc", "\xdd", "\xde", "\xdf",
1688 "\xe0", "\xe1", "\xe2", "\xe3", "\xe4", "\xe5", "\xe6", "\xe7",
1689 "\xe8", "\xe9", "\xea", "\xeb", "\xec", "\xed", "\xee", "\xef",
1690 "\xf0", "\xf1", "\xf2", "\xf3", "\xf4", "\xf5", "\xf6", "\xf7",
1691 "\xf8", "\xf9", "\xfa", "\xfb", "\xfc", "\xfd", "\xfe", "\xff"
1695 json_serialize_string(const char *string
, struct ds
*ds
)
1701 ds_put_char(ds
, '"');
1702 while ((c
= *string
++) != '\0') {
1703 escape
= chars_escaping
[c
];
1704 while ((c2
= *escape
++) != '\0') {
1705 ds_put_char(ds
, c2
);
1708 ds_put_char(ds
, '"');