Skip to content

Commit 9ef16b4

Browse files
committed
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 micropython#17141. Signed-off-by: Alessandro Gatti <[email protected]>
1 parent 7a55cb6 commit 9ef16b4

File tree

2 files changed

+26
-1
lines changed

2 files changed

+26
-1
lines changed

extmod/modjson.c

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -160,7 +160,8 @@ static mp_obj_t mod_json_load(mp_obj_t stream_obj) {
160160
for (;;) {
161161
cont:
162162
if (S_END(s)) {
163-
break;
163+
// Input finished abruptly in the middle of a composite entity.
164+
goto fail;
164165
}
165166
mp_obj_t next = MP_OBJ_NULL;
166167
bool enter = false;

tests/extmod/json_loads.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,3 +71,27 @@ def my_print(o):
7171
my_print(json.loads("[null] a"))
7272
except ValueError:
7373
print("ValueError")
74+
75+
# incomplete object declaration
76+
try:
77+
my_print(json.loads('{"a":0,'))
78+
except ValueError:
79+
print("ValueError")
80+
81+
# incomplete nested array declaration
82+
try:
83+
my_print(json.loads('{"a":0, ['))
84+
except ValueError:
85+
print("ValueError")
86+
87+
# incomplete array declaration
88+
try:
89+
my_print(json.loads('[0,'))
90+
except ValueError:
91+
print("ValueError")
92+
93+
# incomplete nested object declaration
94+
try:
95+
my_print(json.loads('[0, {"a":0, '))
96+
except ValueError:
97+
print("ValueError")

0 commit comments

Comments
 (0)