2 * UCW JSON Library -- Formatter
4 * (c) 2015 Martin Mares <mj@ucw.cz>
6 * This software may be freely distributed and used according to the terms
7 * of the GNU Lesser General Public License.
11 #include <ucw/fastbuf.h>
13 #include <ucw/ff-unicode.h>
14 #include <ucw/unicode.h>
15 #include <ucw-json/json.h>
19 void json_set_output(struct json_context *js, struct fastbuf *fb)
24 static void write_string(struct fastbuf *fb, const char *p)
30 p = utf8_32_get(p, &u);
33 if (u == '"' || u == '\\')
40 // We avoid "\f" nor "\b" and use "\uXXXX" instead
43 case 0x09: bputs(fb, "\\t"); break;
44 case 0x0a: bputs(fb, "\\n"); break;
45 case 0x0d: bputs(fb, "\\r"); break;
47 bprintf(fb, "\\u%04x", u);
56 void json_write_value(struct json_context *js, struct json_node *n)
58 struct fastbuf *fb = js->out_fb;
66 bputs(fb, (n->boolean ? "true" : "false"));
69 // FIXME: Formatting of floats
70 bprintf(fb, "%f", n->number);
73 write_string(fb, n->string);
79 for (size_t i=0; i < GARY_SIZE(n->elements); i++)
83 json_write_value(js, n->elements[i]);
92 for (size_t i=0; i < GARY_SIZE(n->pairs); i++)
96 struct json_pair *p = &n->pairs[i];
97 write_string(fb, p->key);
99 json_write_value(js, p->value);
109 void json_write(struct json_context *js, struct fastbuf *fb, struct json_node *n)
111 json_set_output(js, fb);
112 json_write_value(js, n);