From 753dd86a1a6c00cae4208a47d21c38b3111b5530 Mon Sep 17 00:00:00 2001 From: thejesh23 <35212698+thejesh23@users.noreply.github.com> Date: Fri, 27 Nov 2026 10:13:13 -0800 Subject: [PATCH] gh-162758: Reject a negative idx in the pure Python JSON scanner --- Lib/json/scanner.py | 2 ++ Lib/test/test_json/test_decode.py | 5 +++++ .../Library/2026-11-27-18-13-13.gh-issue-162758.NKF45H.rst | 2 ++ 3 files changed, 9 insertions(+) create mode 100644 Misc/NEWS.d/next/Library/2026-11-27-18-13-13.gh-issue-162758.NKF45H.rst diff --git a/Lib/json/scanner.py b/Lib/json/scanner.py index b484e00be0fd2af..e0afd3a56818936 100644 --- a/Lib/json/scanner.py +++ b/Lib/json/scanner.py @@ -64,6 +64,8 @@ def _scan_once(string, idx): raise StopIteration(idx) def scan_once(string, idx): + if idx < 0: + raise ValueError('idx cannot be negative') try: return _scan_once(string, idx) finally: diff --git a/Lib/test/test_json/test_decode.py b/Lib/test/test_json/test_decode.py index 7bff16ddf2155e9..f6bfc644c7357d6 100644 --- a/Lib/test/test_json/test_decode.py +++ b/Lib/test/test_json/test_decode.py @@ -168,6 +168,11 @@ def test_string_with_utf8_bom(self): def test_negative_index(self): d = self.json.JSONDecoder() self.assertRaises(ValueError, d.raw_decode, 'a'*42, -50000) + for doc, idx in (('1', -1), ('[1]', -1), ('[1]', -3), ('"a"', -3)): + with self.subTest(doc=doc, idx=idx): + with self.assertRaisesRegex(ValueError, + 'idx cannot be negative'): + d.raw_decode(doc, idx) def test_unterminated_string(self): d = self.json.JSONDecoder() diff --git a/Misc/NEWS.d/next/Library/2026-11-27-18-13-13.gh-issue-162758.NKF45H.rst b/Misc/NEWS.d/next/Library/2026-11-27-18-13-13.gh-issue-162758.NKF45H.rst new file mode 100644 index 000000000000000..8a40f69b6a2fa47 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-11-27-18-13-13.gh-issue-162758.NKF45H.rst @@ -0,0 +1,2 @@ +The pure Python :mod:`json` decoder now raises :exc:`ValueError` for a +negative *idx* in :meth:`~json.JSONDecoder.raw_decode`, like the C decoder.