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 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) {
27 jsmntok_t t[8192]; /* We expect no more than 128 tokens */
29 FILE *fh = fopen("../../../../data/test.map", "r");
32 fread(JSON_STRING, sizeof(t), sizeof(t), fh);
33 // we can now close the file
34 fclose(fh); fh = NULL;
35 printf("%s\n", JSON_STRING);
38 r = jsmn_parse(&p, JSON_STRING, strlen(JSON_STRING), t, sizeof(t)/sizeof(t[0]));
39 printf("%s\n", JSON_STRING);
41 printf("Failed to parse JSON: %d\n", r);
45 /* Assume the top-level element is an object */
46 if (r < 1 || t[0].type != JSMN_OBJECT) {
47 printf("Object expected\n");
51 /* Loop over all keys of the root object */
52 for (i = 1; i < r; i++) {
53 if (jsoneq(JSON_STRING, &t[i], "user") == 0) {
54 /* We may use strndup() to fetch string value */
55 printf("- User: %.*s\n", t[i+1].end-t[i+1].start,
56 JSON_STRING + t[i+1].start);
58 } else if (jsoneq(JSON_STRING, &t[i], "admin") == 0) {
59 /* We may additionally check if the value is either "true" or "false" */
60 printf("- Admin: %.*s\n", t[i+1].end-t[i+1].start,
61 JSON_STRING + t[i+1].start);
63 } else if (jsoneq(JSON_STRING, &t[i], "uid") == 0) {
64 /* We may want to do strtol() here to get numeric value */
65 printf("- UID: %.*s\n", t[i+1].end-t[i+1].start,
66 JSON_STRING + t[i+1].start);
68 } else if (jsoneq(JSON_STRING, &t[i], "groups") == 0) {
70 printf("- Groups:\n");
71 if (t[i+1].type != JSMN_ARRAY) {
72 continue; /* We expect groups to be an array of strings */
74 for (j = 0; j < t[i+1].size; j++) {
75 jsmntok_t *g = &t[i+j+2];
76 printf(" * %.*s\n", g->end - g->start, JSON_STRING + g->start);
80 printf("Unexpected key: %.*s\n", t[i].end-t[i].start,
81 JSON_STRING + t[i].start);
87 if (fh != NULL) fclose(fh);