1 #include "../jsmn.h"
2 #include <stdio.h>
3 #include <stdlib.h>
4 #include <string.h>
5 
6 /*
7  * A small example of jsmn parsing when JSON structure is known and number of
8  * tokens is predictable.
9  */
10 
11 static const char *JSON_STRING =
12     "{\"user\": \"johndoe\", \"admin\": false, \"uid\": 1000,\n  "
13     "\"groups\": [\"users\", \"wheel\", \"audio\", \"video\"]}";
14 
jsoneq(const char * json,jsmntok_t * tok,const char * s)15 static int jsoneq(const char *json, jsmntok_t *tok, const char *s) {
16   if (tok->type == JSMN_STRING && (int)strlen(s) == tok->end - tok->start &&
17       strncmp(json + tok->start, s, tok->end - tok->start) == 0) {
18     return 0;
19   }
20   return -1;
21 }
22 
main()23 int main() {
24   int i;
25   int r;
26   jsmn_parser p;
27   jsmntok_t t[128]; /* We expect no more than 128 tokens */
28 
29   jsmn_init(&p);
30   r = jsmn_parse(&p, JSON_STRING, strlen(JSON_STRING), t,
31                  sizeof(t) / sizeof(t[0]));
32   if (r < 0) {
33     printf("Failed to parse JSON: %d\n", r);
34     return 1;
35   }
36 
37   /* Assume the top-level element is an object */
38   if (r < 1 || t[0].type != JSMN_OBJECT) {
39     printf("Object expected\n");
40     return 1;
41   }
42 
43   /* Loop over all keys of the root object */
44   for (i = 1; i < r; i++) {
45     if (jsoneq(JSON_STRING, &t[i], "user") == 0) {
46       /* We may use strndup() to fetch string value */
47       printf("- User: %.*s\n", t[i + 1].end - t[i + 1].start,
48              JSON_STRING + t[i + 1].start);
49       i++;
50     } else if (jsoneq(JSON_STRING, &t[i], "admin") == 0) {
51       /* We may additionally check if the value is either "true" or "false" */
52       printf("- Admin: %.*s\n", t[i + 1].end - t[i + 1].start,
53              JSON_STRING + t[i + 1].start);
54       i++;
55     } else if (jsoneq(JSON_STRING, &t[i], "uid") == 0) {
56       /* We may want to do strtol() here to get numeric value */
57       printf("- UID: %.*s\n", t[i + 1].end - t[i + 1].start,
58              JSON_STRING + t[i + 1].start);
59       i++;
60     } else if (jsoneq(JSON_STRING, &t[i], "groups") == 0) {
61       int j;
62       printf("- Groups:\n");
63       if (t[i + 1].type != JSMN_ARRAY) {
64         continue; /* We expect groups to be an array of strings */
65       }
66       for (j = 0; j < t[i + 1].size; j++) {
67         jsmntok_t *g = &t[i + j + 2];
68         printf("  * %.*s\n", g->end - g->start, JSON_STRING + g->start);
69       }
70       i += t[i + 1].size + 1;
71     } else {
72       printf("Unexpected key: %.*s\n", t[i].end - t[i].start,
73              JSON_STRING + t[i].start);
74     }
75   }
76   return EXIT_SUCCESS;
77 }
78