]>
diplodocus.org Git - nmh/blob - thirdparty/jsmn/example/jsondump.c
8 * An example of reading JSON from stdin and printing its content to stdout.
9 * The output looks like YAML, but I'm not sure if it's really compatible.
12 static int dump(const char *js
, jsmntok_t
*t
, size_t count
, int indent
) {
17 if (t
->type
== JSMN_PRIMITIVE
) {
18 printf("%.*s", t
->end
- t
->start
, js
+t
->start
);
20 } else if (t
->type
== JSMN_STRING
) {
21 printf("'%.*s'", t
->end
- t
->start
, js
+t
->start
);
23 } else if (t
->type
== JSMN_OBJECT
) {
26 for (i
= 0; i
< t
->size
; i
++) {
27 for (k
= 0; k
< indent
; k
++) printf(" ");
28 j
+= dump(js
, t
+1+j
, count
-j
, indent
+1);
30 j
+= dump(js
, t
+1+j
, count
-j
, indent
+1);
34 } else if (t
->type
== JSMN_ARRAY
) {
37 for (i
= 0; i
< t
->size
; i
++) {
38 for (k
= 0; k
< indent
-1; k
++) printf(" ");
40 j
+= dump(js
, t
+1+j
, count
-j
, indent
+1);
62 /* Allocate some tokens as a start */
63 tok
= malloc(sizeof(*tok
) * tokcount
);
65 fprintf(stderr
, "malloc(): errno=%d\n", errno
);
70 /* Read another chunk */
71 r
= fread(buf
, 1, sizeof(buf
), stdin
);
73 fprintf(stderr
, "fread(): %d, errno=%d\n", r
, errno
);
77 if (eof_expected
!= 0) {
80 fprintf(stderr
, "fread(): unexpected EOF\n");
85 js
= realloc(js
, jslen
+ r
+ 1);
87 fprintf(stderr
, "realloc(): errno=%d\n", errno
);
90 strncpy(js
+ jslen
, buf
, r
);
94 r
= jsmn_parse(&p
, js
, jslen
, tok
, tokcount
);
96 if (r
== JSMN_ERROR_NOMEM
) {
97 tokcount
= tokcount
* 2;
98 tok
= realloc(tok
, sizeof(*tok
) * tokcount
);
100 fprintf(stderr
, "realloc(): errno=%d\n", errno
);
106 dump(js
, tok
, p
.toknext
, 0);