From 60a157130724326ae3cd4d44300da1034a69ced9 Mon Sep 17 00:00:00 2001 From: Thejesh <35212698+thejesh23@users.noreply.github.com> Date: Sat, 14 Nov 2026 18:00:38 -0800 Subject: [PATCH 1/2] Report the backslash position for invalid escapes in the Python json decoder The C decoder reports the position of the backslash. The pure Python decoder reported the position of the character after it. --- Lib/json/decoder.py | 2 +- Lib/test/test_json/test_fail.py | 18 ++++++++++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/Lib/json/decoder.py b/Lib/json/decoder.py index ee0464318458117..31f410632d4f87e 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 7f99a6331d36251..76ab6f9ced89016 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), From d4f296f5647e723f14320593d08a0b87ad939e56 Mon Sep 17 00:00:00 2001 From: Thejesh <35212698+thejesh23@users.noreply.github.com> Date: Sat, 14 Nov 2026 18:06:22 -0800 Subject: [PATCH 2/2] Add NEWS entry --- .../next/Library/2026-11-15-02-06-21.gh-issue-162028.jAnDAg.rst | 2 ++ 1 file changed, 2 insertions(+) create mode 100644 Misc/NEWS.d/next/Library/2026-11-15-02-06-21.gh-issue-162028.jAnDAg.rst 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 000000000000000..a52a970039d3df0 --- /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.