10 * A small example of jsmn parsing when JSON structure is known and number of
11 * tokens is predictable.
15 "{\"user\": \"johndoe\", \"admin\": false, \"uid\": 1000,\n "
16 "\"groups\": [\"users\", \"wheel\", \"audio\", \"video\"]}";*/
18 long int filesize(FILE *fp)
\r
20 long int save_pos, size_of_file;
\r
22 save_pos = ftell(fp);
\r
23 fseek(fp, 0L, SEEK_END);
\r
24 size_of_file = ftell(fp);
\r
25 fseek(fp, save_pos, SEEK_SET);
\r
26 return(size_of_file);
\r
29 static int jsoneq(const char *json, jsmntok_t *tok, const char *s) {
30 if (tok->type == JSMN_STRING && (int) strlen(s) == tok->end - tok->start &&
31 strncmp(json + tok->start, s, tok->end - tok->start) == 0) {
42 jsmntok_t t[(BUFSIZ/sizeof(jsmntok_t))*2]; /* We expect no more than 128 tokens */
43 FILE *fh = fopen("../../../../data/test.map", "r");
44 char *json_string = malloc(filesize(fh));
50 fprintf(stderr, "malloc(): errno=%d\n", errno);
53 //printf("\n%d\n\n", sizeof(*t));
54 printf("\n%d", sizeof(*t));
55 printf("\n%d", sizeof(t));
56 printf("\n%d\n\n", sizeof(t)/sizeof(t[0]));
57 z = fread(json_string, 1, filesize(fh), fh);
59 fclose(fh); fh = NULL;
61 json_string[z] = '\0';
62 // we can now close the file
63 //printf("]%s[\n", json_s);
65 //printf("[[%s]]\n", json_string);
68 r = jsmn_parse(&p, json_string, strlen(json_string), t, sizeof(t)/sizeof(t[0]));
69 //t[(BUFSIZ/sizeof(jsmntok_t))*2+1].type=JSMN_OBJECT;
70 printf("[\n%s\n]", json_string);
73 printf("Failed to parse JSON: %d\n", r);
77 /* Assume the top-level element is an object */
78 if (r < 1 || t[0].type != JSMN_OBJECT) {
79 printf("Object expected\n");
83 /* Loop over all keys of the root object */
84 for (i = 1; i < r; i++) {
85 if (jsoneq(json_string, &t[i], "image") == 0) {
86 /* We may use strndup() to fetch string value */
87 printf("- image: %.*s\n", t[i+1].end-t[i+1].start,
88 json_string + t[i+1].start);
90 } else if (jsoneq(json_string, &t[i], "admin") == 0) {
91 /* We may additionally check if the value is either "true" or "false" */
92 printf("- Admin: %.*s\n", t[i+1].end-t[i+1].start,
93 json_string + t[i+1].start);
95 } else if (jsoneq(json_string, &t[i], "uid") == 0) {
96 /* We may want to do strtol() here to get numeric value */
97 printf("- UID: %.*s\n", t[i+1].end-t[i+1].start,
98 json_string + t[i+1].start);
100 } else if (jsoneq(json_string, &t[i], "tilesets") == 0) {
102 printf("- tilesets:\n");
103 if (t[i+1].type != JSMN_ARRAY) {
104 continue; /* We expect groups to be an array of strings */
106 for (j = 0; j < t[i+1].size; j++) {
107 jsmntok_t *g = &t[i+j+2];
108 printf(" * %.*s\n", g->end - g->start, json_string + g->start);
110 i += t[i+1].size + 1;
112 /*printf("Unexpected key: %.*s\n", t[i].end-t[i].start,
113 json_string + t[i].start);*/
119 if (fh != NULL) fclose(fh);