6 * A small example of jsmn parsing when JSON structure is known and number of
7 * tokens is predictable.
10 const char *JSON_STRING =
11 "{\"user\": \"johndoe\", \"admin\": false, \"uid\": 1000,\n "
12 "\"groups\": [\"users\", \"wheel\", \"audio\", \"video\"]}";
14 static int jsoneq(const char *json, jsmntok_t *tok, const char *s) {
15 if (tok->type == JSMN_STRING && (int) strlen(s) == tok->end - tok->start &&
16 strncmp(json + tok->start, s, tok->end - tok->start) == 0) {
26 jsmntok_t t[128]; /* We expect no more than 128 tokens */
29 r = jsmn_parse(&p, JSON_STRING, strlen(JSON_STRING), t, sizeof(t)/sizeof(t[0]));
31 printf("Failed to parse JSON: %d\n", r);
35 /* Assume the top-level element is an object */
36 if (r < 1 || t[0].type != JSMN_OBJECT) {
37 printf("Object expected\n");
41 /* Loop over all keys of the root object */
42 for (i = 1; i < r; i++) {
43 if (jsoneq(JSON_STRING, &t[i], "user") == 0) {
44 /* We may use strndup() to fetch string value */
45 printf("- User: %.*s\n", t[i+1].end-t[i+1].start,
46 JSON_STRING + t[i+1].start);
48 } else if (jsoneq(JSON_STRING, &t[i], "admin") == 0) {
49 /* We may additionally check if the value is either "true" or "false" */
50 printf("- Admin: %.*s\n", t[i+1].end-t[i+1].start,
51 JSON_STRING + t[i+1].start);
53 } else if (jsoneq(JSON_STRING, &t[i], "uid") == 0) {
54 /* We may want to do strtol() here to get numeric value */
55 printf("- UID: %.*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], "groups") == 0) {
60 printf("- Groups:\n");
61 if (t[i+1].type != JSMN_ARRAY) {
62 continue; /* We expect groups to be an array of strings */
64 for (j = 0; j < t[i+1].size; j++) {
65 jsmntok_t *g = &t[i+j+2];
66 printf(" * %.*s\n", g->end - g->start, JSON_STRING + g->start);
70 printf("Unexpected key: %.*s\n", t[i].end-t[i].start,
71 JSON_STRING + t[i].start);