diff --git a/Lib/json/decoder.py b/Lib/json/decoder.py index 44a13fd3965b1a..21a957cd3acf05 100644 --- a/Lib/json/decoder.py +++ b/Lib/json/decoder.py @@ -112,7 +112,7 @@ def py_scanstring(s, end, strict=True, char = _b[esc] except KeyError: msg = "Invalid \\escape: {0!r}".format(esc) - raise JSONDecodeError(msg, s, end) + raise JSONDecodeError(msg, s, end - 1) end += 1 else: uni = _decode_uXXXX(s, end) diff --git a/Lib/test/test_json/test_fail.py b/Lib/test/test_json/test_fail.py index 7f99a6331d3625..76ab6f9ced8901 100644 --- a/Lib/test/test_json/test_fail.py +++ b/Lib/test/test_json/test_fail.py @@ -201,6 +201,24 @@ def test_unexpected_data(self): '%s: line 1 column %d (char %d)' % (msg, idx + 1, idx)) + def test_invalid_escape_position(self): + # The position points to the backslash of the invalid escape. + test_cases = [ + ('"\\a"', 1), + ('"ab\\x"', 3), + ('["\\\'"]', 2), + ('{"k": "v\\ "}', 8), + ] + for data, idx in test_cases: + with self.subTest(data=data): + with self.assertRaises(self.JSONDecodeError) as cm: + self.loads(data) + err = cm.exception + self.assertStartsWith(err.msg, 'Invalid \\escape') + self.assertEqual(err.pos, idx) + self.assertEqual(err.lineno, 1) + self.assertEqual(err.colno, idx + 1) + def test_extra_data(self): test_cases = [ ('[]]', 'Extra data', 2), diff --git a/Misc/NEWS.d/next/Library/2026-11-15-02-06-21.gh-issue-162028.jAnDAg.rst b/Misc/NEWS.d/next/Library/2026-11-15-02-06-21.gh-issue-162028.jAnDAg.rst new file mode 100644 index 00000000000000..a52a970039d3df --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-11-15-02-06-21.gh-issue-162028.jAnDAg.rst @@ -0,0 +1,2 @@ +Fix the position reported by the pure Python :mod:`json` decoder for an +invalid escape. It now points to the backslash, like the C decoder.