From e6f68519b0f96416b1e05f5d7268dcb4e2b26f70 Mon Sep 17 00:00:00 2001 From: Richard Schwab Date: Wed, 3 Apr 2024 00:57:56 +0200 Subject: [PATCH] Allow decoding of escaped forward slashes --- src/mjson.c | 7 +++++++ test/unit_test.c | 7 +++++++ 2 files changed, 14 insertions(+) diff --git a/src/mjson.c b/src/mjson.c index 55ba507..1124e41 100644 --- a/src/mjson.c +++ b/src/mjson.c @@ -318,6 +318,13 @@ static int mjson_unescape(const char *s, int len, char *to, int n) { if (s[i + 2] != '0' || s[i + 3] != '0') return -1; // Too much, give up ((unsigned char *) to)[j] = mjson_unhex_nimble(s + i + 4); i += 5; + } else if (s[i] == '\\' && i + 1 < len && s[i + 1] == '/') { + // Any character may be escaped in a string. This takes care of escaped + // slashes only to minimize added complexity while supporting PHP's + // default json encoding format, as that escapes forward slashes by + // default. + to[j] = '/'; + i++; } else if (s[i] == '\\' && i + 1 < len) { int c = mjson_esc(s[i + 1], 0); if (c == 0) return -1; diff --git a/test/unit_test.c b/test/unit_test.c index 6d5f5bd..9a84807 100644 --- a/test/unit_test.c +++ b/test/unit_test.c @@ -340,6 +340,13 @@ static void test_get_string(void) { ASSERT(mjson_get_string(s, (int) strlen(s), "$[2]", buf, sizeof(buf)) > 0); ASSERT(strcmp(buf, expected) == 0); } + + { + const char *s = "{\"url\":\"https:\\/\\/example.org\\/\"}"; + const char *expected = "https://example.org/"; + ASSERT(mjson_get_string(s, (int) strlen(s), "$.url", buf, sizeof(buf)) == 20); + ASSERT(strcmp(buf, expected) == 0); + } } static void test_print(void) {