Thanks to visit codestin.com
Credit goes to github.com

Skip to content

gh-59598: Ignore leading whitespace in JSONDecoder.raw_decode #117397

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions Doc/library/json.rst
Original file line number Diff line number Diff line change
Expand Up @@ -402,6 +402,9 @@ Encoders and Decoders
This can be used to decode a JSON document from a string that may have
extraneous data at the end.

.. versionchanged:: 3.14
Now ignores any leading whitespace instead of returning an error
Comment on lines +405 to +406
Copy link
Contributor

@eendebakpt eendebakpt Jun 19, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
.. versionchanged:: 3.14
Now ignores any leading whitespace instead of returning an error
.. versionchanged:: next
Leading whitespaces are now ignored instead of raising an exception.



.. class:: JSONEncoder(*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)

Expand Down
10 changes: 7 additions & 3 deletions Lib/json/decoder.py
Original file line number Diff line number Diff line change
Expand Up @@ -341,23 +341,27 @@ def decode(self, s, _w=WHITESPACE.match):
containing a JSON document).

"""
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
obj, end = self.raw_decode(s)
end = _w(s, end).end()
if end != len(s):
raise JSONDecodeError("Extra data", s, end)
return obj

def raw_decode(self, s, idx=0):
def raw_decode(self, s, idx=0, _w=WHITESPACE.match):
"""Decode a JSON document from ``s`` (a ``str`` beginning with
a JSON document) and return a 2-tuple of the Python
representation and the index in ``s`` where the document ended.
Whitespace at the beginning of the document will be ignored.

Optionally, ``idx`` can be used to specify an offset in ``s``
where the document begins.

This can be used to decode a JSON document from a string that may
have extraneous data at the end.

"""
try:
obj, end = self.scan_once(s, idx)
obj, end = self.scan_once(s, idx=_w(s, idx).end())
except StopIteration as err:
raise JSONDecodeError("Expecting value", s, err.value) from None
return obj, end
14 changes: 14 additions & 0 deletions Lib/test/test_json/test_decode.py
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,20 @@ def test_limit_int(self):
with self.assertRaises(ValueError):
self.loads('1' * (maxdigits + 1))

class TestRawDecode:
def test_whitespace(self):
decoder = self.json.JSONDecoder()
self.assertEqual(decoder.raw_decode(' {}'), ({}, 3))
self.assertEqual(decoder.raw_decode(' []'), ([], 4))
self.assertEqual(decoder.raw_decode(' ""'), ('', 5))
s = ' { "key" : "value" , "k":"v" } \n' \
' { "key": "value", "k" :"v"} '
val1, n1 = decoder.raw_decode(s)
val2, n2 = decoder.raw_decode(s[n1:])
self.assertEqual(val1, {"key":"value", "k":"v"})
self.assertEqual(val2, {"key":"value", "k":"v"})
Comment on lines +127 to +138
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
class TestRawDecode:
def test_whitespace(self):
decoder = self.json.JSONDecoder()
self.assertEqual(decoder.raw_decode(' {}'), ({}, 3))
self.assertEqual(decoder.raw_decode(' []'), ([], 4))
self.assertEqual(decoder.raw_decode(' ""'), ('', 5))
s = ' { "key" : "value" , "k":"v" } \n' \
' { "key": "value", "k" :"v"} '
val1, n1 = decoder.raw_decode(s)
val2, n2 = decoder.raw_decode(s[n1:])
self.assertEqual(val1, {"key":"value", "k":"v"})
self.assertEqual(val2, {"key":"value", "k":"v"})
class TestRawDecode:
def test_whitespace(self):
decoder = self.json.JSONDecoder()
self.assertEqual(decoder.raw_decode(' {}'), ({}, 3))
self.assertEqual(decoder.raw_decode(' []'), ([], 4))
self.assertEqual(decoder.raw_decode(' ""'), ('', 5))
s = ' { "key" : "value" , "k":"v" } \n' \
' { "key": "value", "k" :"v"} '
val1, n1 = decoder.raw_decode(s)
val2, n2 = decoder.raw_decode(s[n1:])
self.assertEqual(val1, {"key":"value", "k":"v"})
self.assertEqual(val2, {"key":"value", "k":"v"})

In addition, let's test n1 and n2. And test when there are whitespaces inside the values or keys.


class TestPyDecode(TestDecode, PyTest): pass
class TestCDecode(TestDecode, CTest): pass
class TestPyRawDecode(TestRawDecode, PyTest): pass
class TestCRawDecode(TestRawDecode, CTest): pass
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Ignore leading whitespace in :func:`JSONDecoder.raw_decode`
Loading