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.
11 static int jsoneq(const char *json, jsmntok_t *tok, const char *s) {
12 if (tok->type == JSMN_STRING && (int) strlen(s) == tok->end - tok->start &&
13 strncmp(json + tok->start, s, tok->end - tok->start) == 0) {
19 static int dump(const char *js, jsmntok_t *t, size_t count, int indent) {
24 if (t->type == JSMN_PRIMITIVE) {
25 printf("%.*s", t->end - t->start, js+t->start);
27 } else if (t->type == JSMN_STRING) {
28 if(jsoneq(js, t, "data") == 0 )
30 // printf("[[[[%d|%d]]]]\n", &(t+1)->size, (t+1)->size);
31 printf("\n%.*s[xx[%d|%d]xx]\n", (t+1)->end - (t+1)->start, js+(t+1)->start, &(t+1)->size, (t+1)->size);
33 printf("'%.*s'", t->end - t->start, js+t->start);
35 } else if (t->type == JSMN_OBJECT) {
38 for (i = 0; i < t->size; i++) {
39 for (k = 0; k < indent; k++) printf(" ");
40 j += dump(js, t+1+j, count-j, indent+1);
42 j += dump(js, t+1+j, count-j, indent+1);
46 } else if (t->type == JSMN_ARRAY) {
49 for (i = 0; i < t->size; i++) {
50 for (k = 0; k < indent-1; k++) printf(" ");
52 j += dump(js, t+1+j, count-j, indent+1);
74 /* Allocate some tokens as a start */
75 tok = malloc(sizeof(*tok) * tokcount);
77 fprintf(stderr, "malloc(): errno=%d\n", errno);
82 /* Read another chunk */
83 r = fread(buf, 1, sizeof(buf), stdin);
85 fprintf(stderr, "fread(): %d, errno=%d\n", r, errno);
89 if (eof_expected != 0) {
92 fprintf(stderr, "fread(): unexpected EOF\n");
97 js = realloc(js, jslen + r + 1);
99 fprintf(stderr, "realloc(): errno=%d\n", errno);
102 strncpy(js + jslen, buf, r);
106 r = jsmn_parse(&p, js, jslen, tok, tokcount);
108 if (r == JSMN_ERROR_NOMEM) {
109 tokcount = tokcount * 2;
110 tok = realloc(tok, sizeof(*tok) * tokcount);
112 fprintf(stderr, "realloc(): errno=%d\n", errno);
118 dump(js, tok, p.toknext, 0);