• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h>
4 #include "../jsmn.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, sizeof(t)/sizeof(t[0]));
31 	if (r < 0) {
32 		printf("Failed to parse JSON: %d\n", r);
33 		return 1;
34 	}
35 
36 	/* Assume the top-level element is an object */
37 	if (r < 1 || t[0].type != JSMN_OBJECT) {
38 		printf("Object expected\n");
39 		return 1;
40 	}
41 
42 	/* Loop over all keys of the root object */
43 	for (i = 1; i < r; i++) {
44 		if (jsoneq(JSON_STRING, &t[i], "user") == 0) {
45 			/* We may use strndup() to fetch string value */
46 			printf("- User: %.*s\n", t[i+1].end-t[i+1].start,
47 					JSON_STRING + t[i+1].start);
48 			i++;
49 		} else if (jsoneq(JSON_STRING, &t[i], "admin") == 0) {
50 			/* We may additionally check if the value is either "true" or "false" */
51 			printf("- Admin: %.*s\n", t[i+1].end-t[i+1].start,
52 					JSON_STRING + t[i+1].start);
53 			i++;
54 		} else if (jsoneq(JSON_STRING, &t[i], "uid") == 0) {
55 			/* We may want to do strtol() here to get numeric value */
56 			printf("- UID: %.*s\n", t[i+1].end-t[i+1].start,
57 					JSON_STRING + t[i+1].start);
58 			i++;
59 		} else if (jsoneq(JSON_STRING, &t[i], "groups") == 0) {
60 			int j;
61 			printf("- Groups:\n");
62 			if (t[i+1].type != JSMN_ARRAY) {
63 				continue; /* We expect groups to be an array of strings */
64 			}
65 			for (j = 0; j < t[i+1].size; j++) {
66 				jsmntok_t *g = &t[i+j+2];
67 				printf("  * %.*s\n", g->end - g->start, JSON_STRING + g->start);
68 			}
69 			i += t[i+1].size + 1;
70 		} else {
71 			printf("Unexpected key: %.*s\n", t[i].end-t[i].start,
72 					JSON_STRING + t[i].start);
73 		}
74 	}
75 	return EXIT_SUCCESS;
76 }
77