diff options
author | Alessandro Gatti <a.gatti@frob.it> | 2025-04-17 16:56:11 +0200 |
---|---|---|
committer | Alessandro Gatti <a.gatti@frob.it> | 2025-05-19 02:09:40 +0200 |
commit | 9ef16b466bf980a3b3e0980e7d010b0b9130569b (patch) | |
tree | e607bcd3538751be3a0b51e058bbaa7d856f247e | |
parent | 7a55cb6b364fdbc2f3291456643bd640ba566ec9 (diff) | |
download | micropython-9ef16b466bf980a3b3e0980e7d010b0b9130569b.tar.gz micropython-9ef16b466bf980a3b3e0980e7d010b0b9130569b.zip |
extmod/modjson: Detect unterminated composite entities.
This commit makes the JSON parser raise an exception when handling
objects or arrays whose declaration is incomplete, as in missing the
closing marker (brace or bracket) and if the missing marker would have
been the last non-whitespace character in the incoming string.
Since CPython's JSON parser would raise an exception in such a case,
unlike MicroPython's, this commit aligns MicroPython's behaviour with
CPython.
This commit fixes issue #17141.
Signed-off-by: Alessandro Gatti <a.gatti@frob.it>
-rw-r--r-- | extmod/modjson.c | 3 | ||||
-rw-r--r-- | tests/extmod/json_loads.py | 24 |
2 files changed, 26 insertions, 1 deletions
diff --git a/extmod/modjson.c b/extmod/modjson.c index e655a02bc0..11aedd1983 100644 --- a/extmod/modjson.c +++ b/extmod/modjson.c @@ -160,7 +160,8 @@ static mp_obj_t mod_json_load(mp_obj_t stream_obj) { for (;;) { cont: if (S_END(s)) { - break; + // Input finished abruptly in the middle of a composite entity. + goto fail; } mp_obj_t next = MP_OBJ_NULL; bool enter = false; diff --git a/tests/extmod/json_loads.py b/tests/extmod/json_loads.py index f9073c121e..095e67d740 100644 --- a/tests/extmod/json_loads.py +++ b/tests/extmod/json_loads.py @@ -71,3 +71,27 @@ try: my_print(json.loads("[null] a")) except ValueError: print("ValueError") + +# incomplete object declaration +try: + my_print(json.loads('{"a":0,')) +except ValueError: + print("ValueError") + +# incomplete nested array declaration +try: + my_print(json.loads('{"a":0, [')) +except ValueError: + print("ValueError") + +# incomplete array declaration +try: + my_print(json.loads('[0,')) +except ValueError: + print("ValueError") + +# incomplete nested object declaration +try: + my_print(json.loads('[0, {"a":0, ')) +except ValueError: + print("ValueError") |