xref: /freebsd/contrib/ntp/libjsmn/example/simple.c (revision a0ee8cc6)
1 #include <stdio.h>
2 #include <string.h>
3 #include "../jsmn.h"
4 
5 /*
6  * A small example of jsmn parsing when JSON structure is known and number of
7  * tokens is predictable.
8  */
9 
10 const char *JSON_STRING =
11 	"{\"user\": \"johndoe\", \"admin\": false, \"uid\": 1000,\n  "
12 	"\"groups\": [\"users\", \"wheel\", \"audio\", \"video\"]}";
13 
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) {
17 		return 0;
18 	}
19 	return -1;
20 }
21 
22 int main() {
23 	int i;
24 	int r;
25 	jsmn_parser p;
26 	jsmntok_t t[128]; /* We expect no more than 128 tokens */
27 
28 	jsmn_init(&p);
29 	r = jsmn_parse(&p, JSON_STRING, strlen(JSON_STRING), t, sizeof(t)/sizeof(t[0]));
30 	if (r < 0) {
31 		printf("Failed to parse JSON: %d\n", r);
32 		return 1;
33 	}
34 
35 	/* Assume the top-level element is an object */
36 	if (r < 1 || t[0].type != JSMN_OBJECT) {
37 		printf("Object expected\n");
38 		return 1;
39 	}
40 
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);
47 			i++;
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);
52 			i++;
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);
57 			i++;
58 		} else if (jsoneq(JSON_STRING, &t[i], "groups") == 0) {
59 			int j;
60 			printf("- Groups:\n");
61 			if (t[i+1].type != JSMN_ARRAY) {
62 				continue; /* We expect groups to be an array of strings */
63 			}
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);
67 			}
68 			i += t[i+1].size + 1;
69 		} else {
70 			printf("Unexpected key: %.*s\n", t[i].end-t[i].start,
71 					JSON_STRING + t[i].start);
72 		}
73 	}
74 	return 0;
75 }
76