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[2048]; /* We expect no more than 128 tokens */
43 //memset(JSON_S, 0, sizeof(JSON_S));
47 fread(JSON_S, sizeof(char), filesize(fh), fh);
48 // we can now close the file
49 //printf("]%s[\n", JSON_S);
51 //printf("[[%s]]\n", JSON_STRING);
54 r = jsmn_parse(&p, JSON_STRING, filesize(fh), t, sizeof(t)/sizeof(t[0]));
55 fclose(fh); fh = NULL;
56 printf("%s", JSON_STRING);
58 printf("Failed to parse JSON: %d\n", r);
62 /* Assume the top-level element is an object */
63 if (r < 1 || t[0].type != JSMN_OBJECT) {
64 printf("Object expected\n");
68 /* Loop over all keys of the root object */
69 for (i = 1; i < r; i++) {
70 if (jsoneq(JSON_STRING, &t[i], "image") == 0) {
71 /* We may use strndup() to fetch string value */
72 printf("- image: %.*s\n", t[i+1].end-t[i+1].start,
73 JSON_STRING + t[i+1].start);
75 } else if (jsoneq(JSON_STRING, &t[i], "admin") == 0) {
76 /* We may additionally check if the value is either "true" or "false" */
77 printf("- Admin: %.*s\n", t[i+1].end-t[i+1].start,
78 JSON_STRING + t[i+1].start);
80 } else if (jsoneq(JSON_STRING, &t[i], "uid") == 0) {
81 /* We may want to do strtol() here to get numeric value */
82 printf("- UID: %.*s\n", t[i+1].end-t[i+1].start,
83 JSON_STRING + t[i+1].start);
85 } else if (jsoneq(JSON_STRING, &t[i], "tilesets") == 0) {
87 printf("- tilesets:\n");
88 if (t[i+1].type != JSMN_ARRAY) {
89 continue; /* We expect groups to be an array of strings */
91 for (j = 0; j < t[i+1].size; j++) {
92 jsmntok_t *g = &t[i+j+2];
93 printf(" * %.*s\n", g->end - g->start, JSON_STRING + g->start);
97 printf("Unexpected key: %.*s\n", t[i].end-t[i].start,
98 JSON_STRING + t[i].start);
104 if (fh != NULL) fclose(fh);