7 * A small example of jsmn parsing when JSON structure is known and number of
8 * tokens is predictable.
12 "{\"user\": \"johndoe\", \"admin\": false, \"uid\": 1000,\n "
13 "\"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) {
41 FILE *fh = fopen("../../../../data/test.map", "r");
42 jsmntok_t *t; /* We expect no more than 128 tokens */
43 size_t tokcount = 2048;
44 /* Allocate some tokens as a start */
45 t = malloc(sizeof(*t) * tokcount);
46 //memset(JSON_S, 0, sizeof(JSON_S));
50 fread(JSON_S, 1, filesize(fh), fh);
51 // we can now close the file
52 //printf("]%s[\n", JSON_S);
54 //printf("[[%s]]\n", JSON_STRING);
57 r = jsmn_parse(&p, JSON_STRING, filesize(fh), t, sizeof(t)/sizeof(t[0]));
58 fclose(fh); fh = NULL;
59 printf("%s", JSON_STRING);
61 printf("Failed to parse JSON: %d\n", r);
65 /* Assume the top-level element is an object */
66 if (r < 1 || t[0].type != JSMN_OBJECT) {
67 printf("Object expected\n");
71 /* Loop over all keys of the root object */
72 for (i = 1; i < r; i++) {
73 if (jsoneq(JSON_STRING, &t[i], "image") == 0) {
74 /* We may use strndup() to fetch string value */
75 printf("- image: %.*s\n", t[i+1].end-t[i+1].start,
76 JSON_STRING + t[i+1].start);
78 } else if (jsoneq(JSON_STRING, &t[i], "admin") == 0) {
79 /* We may additionally check if the value is either "true" or "false" */
80 printf("- Admin: %.*s\n", t[i+1].end-t[i+1].start,
81 JSON_STRING + t[i+1].start);
83 } else if (jsoneq(JSON_STRING, &t[i], "uid") == 0) {
84 /* We may want to do strtol() here to get numeric value */
85 printf("- UID: %.*s\n", t[i+1].end-t[i+1].start,
86 JSON_STRING + t[i+1].start);
88 } else if (jsoneq(JSON_STRING, &t[i], "tilesets") == 0) {
90 printf("- tilesets:\n");
91 if (t[i+1].type != JSMN_ARRAY) {
92 continue; /* We expect groups to be an array of strings */
94 for (j = 0; j < t[i+1].size; j++) {
95 jsmntok_t *g = &t[i+j+2];
96 printf(" * %.*s\n", g->end - g->start, JSON_STRING + g->start);
100 printf("Unexpected key: %.*s\n", t[i].end-t[i].start,
101 JSON_STRING + t[i].start);
107 if (fh != NULL) fclose(fh);