Skip to content

Instantly share code, notes, and snippets.

@Miliox
Created June 15, 2017 13:38
Show Gist options
  • Save Miliox/ddffa1f911b0a63a7d20dea14ab608a9 to your computer and use it in GitHub Desktop.
Save Miliox/ddffa1f911b0a63a7d20dea14ab608a9 to your computer and use it in GitHub Desktop.
JSON C Parsing Example
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "jsmn.h"
char* types[] = {"UNDEFINED", "OBJECT", "ARRAY", "STRING", "PRIMITIVE"};
int main() {
char* json = NULL;
size_t len = 0;
getline(&json, &len, stdin);
jsmn_parser parser;
jsmntok_t tokens[32];
jsmn_init(&parser);
int count = jsmn_parse(&parser, json, strlen(json), tokens, 32);
if (count > 0) {
for (int i = 0; i < count; i++) {
printf("token %d:\n", i);
printf(" type: %s\n", types[tokens[i].type]);
printf(" size: %d\n", tokens[i].size);
printf(" value: ");
fwrite(json + tokens[i].start,
tokens[i].end - tokens[i].start,
1, stdout);
printf("\n\n");
}
}
else if (count < 0) {
fprintf(stderr, "error: parser failed");
if (count == JSMN_ERROR_INVAL) {
fprintf(stderr, " by bad token.");
} else if (count == JSMN_ERROR_NOMEM) {
fprintf(stderr, " by not enought tokens.");
} else if (count == JSMN_ERROR_PART) {
fprintf(stderr, " by json too short.");
}
fprintf(stderr, "\n");
}
free(json);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment