Home | History | Annotate | Line # | Download | only in example
      1 /*	$NetBSD: simple.c,v 1.2 2020/05/25 20:47:24 christos Exp $	*/
      2 
      3 #include <stdio.h>
      4 #include <string.h>
      5 #include "../jsmn.h"
      6 
      7 /*
      8  * A small example of jsmn parsing when JSON structure is known and number of
      9  * tokens is predictable.
     10  */
     11 
     12 const char *JSON_STRING =
     13 	"{\"user\": \"johndoe\", \"admin\": false, \"uid\": 1000,\n  "
     14 	"\"groups\": [\"users\", \"wheel\", \"audio\", \"video\"]}";
     15 
     16 static int jsoneq(const char *json, jsmntok_t *tok, const char *s) {
     17 	if (tok->type == JSMN_STRING && (int) strlen(s) == tok->end - tok->start &&
     18 			strncmp(json + tok->start, s, tok->end - tok->start) == 0) {
     19 		return 0;
     20 	}
     21 	return -1;
     22 }
     23 
     24 int main() {
     25 	int i;
     26 	int r;
     27 	jsmn_parser p;
     28 	jsmntok_t t[128]; /* We expect no more than 128 tokens */
     29 
     30 	jsmn_init(&p);
     31 	r = jsmn_parse(&p, JSON_STRING, strlen(JSON_STRING), t, 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 0;
     77 }
     78