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\"]}";*/
15 long int filesize(FILE *fp)
\r
17 long int save_pos, size_of_file;
\r
19 save_pos = ftell(fp);
\r
20 fseek(fp, 0L, SEEK_END);
\r
21 size_of_file = ftell(fp);
\r
22 fseek(fp, save_pos, SEEK_SET);
\r
23 return(size_of_file);
\r
26 static int jsoneq(const char *json, jsmntok_t *tok, const char *s) {
27 if (tok->type == JSMN_STRING && (int) strlen(s) == tok->end - tok->start &&
28 strncmp(json + tok->start, s, tok->end - tok->start) == 0) {
40 jsmntok_t t[2048]; /* We expect no more than 128 tokens */
41 FILE *fh = fopen("../../../../data/test.map", "r");
43 char *json_string = malloc(filesize(fh));
44 //memset(json_string, 0, sizeof(*json_string));
48 z = fread(json_string, 1, filesize(fh), fh);
49 printf("[[%d]]\n", z);
50 json_string[z] = '\0';
51 // we can now close the file
52 //printf("]%s[\n", json_s);
54 //printf("[[%s]]\n", json_string);
57 printf("[\n%s\n]", json_string);
58 r = jsmn_parse(&p, json_string, filesize(fh), t, sizeof(t)/sizeof(t[0]));
59 fclose(fh); fh = NULL;
60 //printf("[\n%s\n]", json_string);
62 printf("Failed to parse JSON: %d\n", r);
66 /* Assume the top-level element is an object */
67 if (r < 1 || t[0].type != JSMN_OBJECT) {
68 printf("Object expected\n");
72 /* Loop over all keys of the root object */
73 for (i = 1; i < r; i++) {
74 if (jsoneq(json_string, &t[i], "image") == 0) {
75 /* We may use strndup() to fetch string value */
76 printf("- image: %.*s\n", t[i+1].end-t[i+1].start,
77 json_string + t[i+1].start);
79 } else if (jsoneq(json_string, &t[i], "admin") == 0) {
80 /* We may additionally check if the value is either "true" or "false" */
81 printf("- Admin: %.*s\n", t[i+1].end-t[i+1].start,
82 json_string + t[i+1].start);
84 } else if (jsoneq(json_string, &t[i], "uid") == 0) {
85 /* We may want to do strtol() here to get numeric value */
86 printf("- UID: %.*s\n", t[i+1].end-t[i+1].start,
87 json_string + t[i+1].start);
89 } else if (jsoneq(json_string, &t[i], "tilesets") == 0) {
91 printf("- tilesets:\n");
92 if (t[i+1].type != JSMN_ARRAY) {
93 continue; /* We expect groups to be an array of strings */
95 for (j = 0; j < t[i+1].size; j++) {
96 jsmntok_t *g = &t[i+j+2];
97 printf(" * %.*s\n", g->end - g->start, json_string + g->start);
101 printf("Unexpected key: %.*s\n", t[i].end-t[i].start,
102 json_string + t[i].start);
108 if (fh != NULL) fclose(fh);