From 0661f5921a4b0bc1e581e4f4285a56a3e0eec6a3 Mon Sep 17 00:00:00 2001 From: cpq Date: Mon, 29 Aug 2022 12:40:50 +0100 Subject: [PATCH] Fix #1690 - mg_json_get for keys with the same prefix --- mongoose.c | 4 +++- src/json.c | 4 +++- test/unit_test.c | 5 +++++ 3 files changed, 11 insertions(+), 2 deletions(-) diff --git a/mongoose.c b/mongoose.c index 228f860a..88f856b2 100644 --- a/mongoose.c +++ b/mongoose.c @@ -2565,8 +2565,10 @@ int mg_json_get(struct mg_str json, const char *path, int *toklen) { int n = mg_pass_string(&s[i + 1], len - i - 1); if (n < 0) return n; if (i + 1 + n >= len) return MG_JSON_NOT_FOUND; - // printf("K[%.*s] %d %d\n", n, &s[i + 1], depth, ed); + // printf("K[%.*s] %d %d %d\n", n, &s[i + 1], n, depth, ed); if (depth == ed && path[pos - 1] == '.' && + (path[pos + n] == '\0' || path[pos + n] == '.' || + path[pos + n] == '[') && strncmp(&s[i + 1], &path[pos], (size_t) n) == 0) { pos += n; } diff --git a/src/json.c b/src/json.c index 761ca609..c5da6853 100644 --- a/src/json.c +++ b/src/json.c @@ -169,8 +169,10 @@ int mg_json_get(struct mg_str json, const char *path, int *toklen) { int n = mg_pass_string(&s[i + 1], len - i - 1); if (n < 0) return n; if (i + 1 + n >= len) return MG_JSON_NOT_FOUND; - // printf("K[%.*s] %d %d\n", n, &s[i + 1], depth, ed); + // printf("K[%.*s] %d %d %d\n", n, &s[i + 1], n, depth, ed); if (depth == ed && path[pos - 1] == '.' && + (path[pos + n] == '\0' || path[pos + n] == '.' || + path[pos + n] == '[') && strncmp(&s[i + 1], &path[pos], (size_t) n) == 0) { pos += n; } diff --git a/test/unit_test.c b/test/unit_test.c index 7852939f..a34842e6 100644 --- a/test/unit_test.c +++ b/test/unit_test.c @@ -2490,6 +2490,11 @@ static void test_json(void) { ASSERT((str = mg_json_get_hex(json, "$[1]", &len)) != NULL); ASSERT(len == 5 && memcmp(str, "\x01\x00\x02hi", (size_t) len) == 0); free(str); + + json = mg_str("{\"a\":[1,2,3], \"ab\": 2}"); + ASSERT(mg_json_get_long(json, "$.a[0]", -42) == 1); + ASSERT(mg_json_get_long(json, "$.ab", -42) == 2); + ASSERT(mg_json_get_long(json, "$.ac", -42) == -42); } }