https://github.com/python/cpython/commit/5e18bfcf3e27d69731384f7240e063f7eac4ef50
commit: 5e18bfcf3e27d69731384f7240e063f7eac4ef50
branch: main
author: Thejesh <[email protected]>
committer: vstinner <[email protected]>
date: 2026-11-16T18:00:08+01:00
summary:
gh-162028: Fix the pure Python JSON decoder error position for invalid escapes
(#162029)
The C decoder reports the position of the backslash. The pure Python
decoder reported the position of the character after it.
files:
A Misc/NEWS.d/next/Library/2026-11-15-02-06-21.gh-issue-162028.jAnDAg.rst
M Lib/json/decoder.py
M Lib/test/test_json/test_fail.py
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),
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.
_______________________________________________
Python-checkins mailing list -- [email protected]
To unsubscribe send an email to [email protected]
https://mail.python.org/mailman3//lists/python-checkins.python.org
Member address: [email protected]