From 5c50e9dd129d197f5c7192a937497a978ad76421 Mon Sep 17 00:00:00 2001 From: Thejesh Date: Mon, 16 Nov 2026 09:00:08 -0800 Subject: [PATCH] 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 5e18bfcf3e27d69731384f7240e063f7eac4ef50) Co-authored-by: Thejesh --- Lib/json/decoder.py | 2 +- Lib/test/test_json/test_fail.py | 18 ++++++++++++++++++ ...6-11-15-02-06-21.gh-issue-162028.jAnDAg.rst | 2 ++ 3 files changed, 21 insertions(+), 1 deletion(-) create mode 100644 Misc/NEWS.d/next/Library/2026-11-15-02-06-21.gh-issue-162028.jAnDAg.rst diff --git a/Lib/json/decoder.py b/Lib/json/decoder.py index ee046431845811..31f410632d4f87 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.