simple.c revision 290000
1893SN/A#include <stdio.h>
22362SN/A#include <string.h>
3893SN/A#include "../jsmn.h"
4893SN/A
5893SN/A/*
6893SN/A * A small example of jsmn parsing when JSON structure is known and number of
72362SN/A * tokens is predictable.
8893SN/A */
92362SN/A
10893SN/Aconst char *JSON_STRING =
11893SN/A	"{\"user\": \"johndoe\", \"admin\": false, \"uid\": 1000,\n  "
12893SN/A	"\"groups\": [\"users\", \"wheel\", \"audio\", \"video\"]}";
13893SN/A
14893SN/Astatic int jsoneq(const char *json, jsmntok_t *tok, const char *s) {
15893SN/A	if (tok->type == JSMN_STRING && (int) strlen(s) == tok->end - tok->start &&
16893SN/A			strncmp(json + tok->start, s, tok->end - tok->start) == 0) {
17893SN/A		return 0;
18893SN/A	}
19893SN/A	return -1;
20893SN/A}
212362SN/A
222362SN/Aint main() {
232362SN/A	int i;
24893SN/A	int r;
25893SN/A	jsmn_parser p;
26893SN/A	jsmntok_t t[128]; /* We expect no more than 128 tokens */
27893SN/A
28893SN/A	jsmn_init(&p);
29893SN/A	r = jsmn_parse(&p, JSON_STRING, strlen(JSON_STRING), t, sizeof(t)/sizeof(t[0]));
30893SN/A	if (r < 0) {
31893SN/A		printf("Failed to parse JSON: %d\n", r);
32893SN/A		return 1;
33893SN/A	}
34893SN/A
35893SN/A	/* Assume the top-level element is an object */
36893SN/A	if (r < 1 || t[0].type != JSMN_OBJECT) {
37893SN/A		printf("Object expected\n");
38893SN/A		return 1;
39893SN/A	}
40893SN/A
41893SN/A	/* Loop over all keys of the root object */
42893SN/A	for (i = 1; i < r; i++) {
43893SN/A		if (jsoneq(JSON_STRING, &t[i], "user") == 0) {
44893SN/A			/* We may use strndup() to fetch string value */
45893SN/A			printf("- User: %.*s\n", t[i+1].end-t[i+1].start,
46893SN/A					JSON_STRING + t[i+1].start);
47893SN/A			i++;
48893SN/A		} else if (jsoneq(JSON_STRING, &t[i], "admin") == 0) {
49908SN/A			/* We may additionally check if the value is either "true" or "false" */
50893SN/A			printf("- Admin: %.*s\n", t[i+1].end-t[i+1].start,
51893SN/A					JSON_STRING + t[i+1].start);
52893SN/A			i++;
53893SN/A		} else if (jsoneq(JSON_STRING, &t[i], "uid") == 0) {
54893SN/A			/* We may want to do strtol() here to get numeric value */
55893SN/A			printf("- UID: %.*s\n", t[i+1].end-t[i+1].start,
56893SN/A					JSON_STRING + t[i+1].start);
57893SN/A			i++;
58893SN/A		} else if (jsoneq(JSON_STRING, &t[i], "groups") == 0) {
59908SN/A			int j;
60893SN/A			printf("- Groups:\n");
61908SN/A			if (t[i+1].type != JSMN_ARRAY) {
62893SN/A				continue; /* We expect groups to be an array of strings */
63908SN/A			}
64893SN/A			for (j = 0; j < t[i+1].size; j++) {
65893SN/A				jsmntok_t *g = &t[i+j+2];
66893SN/A				printf("  * %.*s\n", g->end - g->start, JSON_STRING + g->start);
67893SN/A			}
68893SN/A			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