Demo: changed to read from '.js' file

master
Serge A. Zaitsev 14 years ago
parent a20a5aff1c
commit aa97d8b599

@ -10,57 +10,87 @@
#define NUM_TOKENS 20 #define NUM_TOKENS 20
static void json_dump_obj(jsontok_t *obj, const unsigned char *js) { static void json_dump_obj(jsontok_t *obj, const char *js) {
size_t len; size_t len;
printf("[%d,%d]", obj->start, obj->end); if (obj->end < 0 || obj->start < 0) {
len = (size_t) (obj->end - obj->start); return;
}
len = obj->end - obj->start;
printf("[%d,%d]\t", obj->start, obj->end);
char *type; char *type;
switch (obj->type) { switch (obj->type) {
case JSON_OTHER: case JSON_OTHER:
type = "other"; type = "(?)";
break; break;
case JSON_NUMBER: case JSON_NUMBER:
type = "number"; type = "(N)";
break; break;
case JSON_STRING: case JSON_STRING:
type = "string"; type = "(S)";
break; break;
case JSON_ARRAY: case JSON_ARRAY:
type = "array"; type = "(A)";
break; break;
case JSON_OBJECT: case JSON_OBJECT:
type = "object"; type = "(O)";
break; break;
} }
printf("%s ", type); printf("%s ", type);
if (len > 0) {
char *s = strndup((const char *) &js[obj->start], len); char *s = strndup((const char *) &js[obj->start], len);
printf("%s", s); printf("%s\n", s);
free(s); free(s);
} }
printf("\n");
}
int main(void) { int main(int argc, char *argv[]) {
int i; int i;
jsontok_t tokens[NUM_TOKENS]; jsontok_t tokens[NUM_TOKENS];
FILE *f;
int filesize = 0;
char *js = NULL;
if (argc != 2) {
fprintf(stderr, "Usage: ./demo <file.js>\n");
exit(EXIT_SUCCESS);
}
f = fopen(argv[1], "r");
if (f == NULL) {
fprintf(stderr, "Failed to open file `%s`\n", argv[1]);
exit(EXIT_FAILURE);
}
const unsigned char *js = (unsigned char *) while (1) {
"{" int r;
"\"foo\": \"bar\"," char buf[BUFSIZ];
"\"bar\": [1,2, 3]," r = fread(buf, 1, BUFSIZ, f);
"\"obj\": { \"true\": false}" if (r <= 0) {
"}"; break;
}
js = (char *) realloc(js, filesize + r);
if (js == NULL) {
fprintf(stderr, "Cannot allocate anough memory\n");
fclose(f);
exit(EXIT_FAILURE);
}
memcpy(js + filesize, buf, r);
filesize += r;
}
fclose(f);
jsmn_parse(js, tokens, NUM_TOKENS, NULL); jsmn_parse((unsigned char *) js, tokens, NUM_TOKENS, NULL);
for (i = 0; i<NUM_TOKENS; i++) { for (i = 0; i<NUM_TOKENS; i++) {
json_dump_obj(&tokens[i], js); json_dump_obj(&tokens[i], js);
} }
free(js);
return 0; return 0;
} }

Loading…
Cancel
Save