Skip to content

Commit b6e87ee

Browse files
[3.15] gh-162028: Fix the pure Python JSON decoder error position for invalid escapes (GH-162029) (#162122)
gh-162028: Fix the pure Python JSON decoder error position for invalid escapes (GH-162029) The C decoder reports the position of the backslash. The pure Python decoder reported the position of the character after it. (cherry picked from commit 5e18bfc) Co-authored-by: Thejesh <thejesh36@gmail.com>
1 parent 64974c3 commit b6e87ee

3 files changed

Lines changed: 21 additions & 1 deletion

File tree

‎Lib/json/decoder.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -112,7 +112,7 @@ def py_scanstring(s, end, strict=True,
112112
char = _b[esc]
113113
except KeyError:
114114
msg = "Invalid \\escape: {0!r}".format(esc)
115-
raise JSONDecodeError(msg, s, end)
115+
raise JSONDecodeError(msg, s, end - 1)
116116
end += 1
117117
else:
118118
uni = _decode_uXXXX(s, end)

‎Lib/test/test_json/test_fail.py‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -201,6 +201,24 @@ def test_unexpected_data(self):
201201
'%s: line 1 column %d (char %d)' %
202202
(msg, idx + 1, idx))
203203

204+
def test_invalid_escape_position(self):
205+
# The position points to the backslash of the invalid escape.
206+
test_cases = [
207+
('"\\a"', 1),
208+
('"ab\\x"', 3),
209+
('["\\\'"]', 2),
210+
('{"k": "v\\ "}', 8),
211+
]
212+
for data, idx in test_cases:
213+
with self.subTest(data=data):
214+
with self.assertRaises(self.JSONDecodeError) as cm:
215+
self.loads(data)
216+
err = cm.exception
217+
self.assertStartsWith(err.msg, 'Invalid \\escape')
218+
self.assertEqual(err.pos, idx)
219+
self.assertEqual(err.lineno, 1)
220+
self.assertEqual(err.colno, idx + 1)
221+
204222
def test_extra_data(self):
205223
test_cases = [
206224
('[]]', 'Extra data', 2),
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix the position reported by the pure Python :mod:`json` decoder for an
2+
invalid escape. It now points to the backslash, like the C decoder.

0 commit comments

Comments
 (0)