From 91d7389ec80c742a589bfed25e62aa5f95d2f0f9 Mon Sep 17 00:00:00 2001 From: "Serge A. Zaitsev" Date: Mon, 17 Nov 2014 15:36:18 +0200 Subject: [PATCH] added some tests for key/values nodes and added some stricter validations --- jsmn.c | 8 ++++++++ jsmn_test.c | 44 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 52 insertions(+) diff --git a/jsmn.c b/jsmn.c index 412c3c2..83353bd 100644 --- a/jsmn.c +++ b/jsmn.c @@ -262,6 +262,14 @@ jsmnerr_t jsmn_parse(jsmn_parser *parser, const char *js, size_t len, case '-': case '0': case '1' : case '2': case '3' : case '4': case '5': case '6': case '7' : case '8': case '9': case 't': case 'f': case 'n' : + /* And they must not be keys of the object */ + if (tokens != NULL) { + jsmntok_t *t = &tokens[parser->toksuper]; + if (t->type == JSMN_OBJECT || + (t->type == JSMN_STRING && t->size != 0)) { + return JSMN_ERROR_INVAL; + } + } #else /* In non-strict mode every unquoted value is a primitive */ default: diff --git a/jsmn_test.c b/jsmn_test.c index 7fbcee1..36d04e3 100644 --- a/jsmn_test.c +++ b/jsmn_test.c @@ -490,6 +490,49 @@ int test_count() { return 0; } +int test_keyvalue() { + const char *js; + int r; + jsmn_parser p; + jsmntok_t tokens[10]; + + js = "{\"a\": 0, \"b\": \"c\"}"; + + jsmn_init(&p); + r = jsmn_parse(&p, js, strlen(js), tokens, 10); + check(r == 5); + check(tokens[0].size == 2); /* two keys */ + check(tokens[1].size == 1 && tokens[3].size == 1); /* one value per key */ + check(tokens[2].size == 0 && tokens[4].size == 0); /* values have zero size */ + + js = "{\"a\"\n0}"; + jsmn_init(&p); + r = jsmn_parse(&p, js, strlen(js), tokens, 10); + check(r == JSMN_ERROR_INVAL); + + js = "{\"a\", 0}"; + jsmn_init(&p); + r = jsmn_parse(&p, js, strlen(js), tokens, 10); + check(r == JSMN_ERROR_INVAL); + + js = "{\"a\": {2}}"; + jsmn_init(&p); + r = jsmn_parse(&p, js, strlen(js), tokens, 10); + check(r == JSMN_ERROR_INVAL); + + js = "{\"a\": {2: 3}}"; + jsmn_init(&p); + r = jsmn_parse(&p, js, strlen(js), tokens, 10); + check(r == JSMN_ERROR_INVAL); + + + js = "{\"a\": {\"a\": 2 3}}"; + jsmn_init(&p); + r = jsmn_parse(&p, js, strlen(js), tokens, 10); + check(r == JSMN_ERROR_INVAL); + return 0; +} + /** A huge redefinition of everything to include jsmn in non-script mode */ #define jsmn_init jsmn_init_nonstrict #define jsmn_parse jsmn_parse_nonstrict @@ -548,6 +591,7 @@ int main() { test(test_issue_22, "test issue #22"); test(test_count, "test tokens count estimation"); test(test_nonstrict, "test for non-strict mode"); + test(test_keyvalue, "test for keys/values"); printf("\nPASSED: %d\nFAILED: %d\n", test_passed, test_failed); return 0; }