Skip to content

Commit a0e768c

Browse files
committed
#19307: Improve error message for json.load(s) while passing objects of the wrong type.
1 parent 4ea16e5 commit a0e768c

File tree

3 files changed

+14
-1
lines changed

3 files changed

+14
-1
lines changed

Lib/json/__init__.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -310,6 +310,9 @@ def loads(s, encoding=None, cls=None, object_hook=None, parse_float=None,
310310
The ``encoding`` argument is ignored and deprecated.
311311
312312
"""
313+
if not isinstance(s, str):
314+
raise TypeError('the JSON object must be str, not {!r}'.format(
315+
s.__class__.__name__))
313316
if (cls is None and object_hook is None and
314317
parse_int is None and parse_float is None and
315318
parse_constant is None and object_pairs_hook is None and not kw):

Lib/test/test_json/test_decode.py

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import decimal
2-
from io import StringIO
2+
from io import StringIO, BytesIO
33
from collections import OrderedDict
44
from test.test_json import PyTest, CTest
55

@@ -70,5 +70,12 @@ def test_invalid_escape(self):
7070
msg = 'escape'
7171
self.assertRaisesRegex(ValueError, msg, self.loads, s)
7272

73+
def test_invalid_input_type(self):
74+
msg = 'the JSON object must be str'
75+
for value in [1, 3.14, b'bytes', b'\xff\x00', [], {}, None]:
76+
self.assertRaisesRegex(TypeError, msg, self.loads, value)
77+
with self.assertRaisesRegex(TypeError, msg):
78+
self.json.load(BytesIO(b'[1,2,3]'))
79+
7380
class TestPyDecode(TestDecode, PyTest): pass
7481
class TestCDecode(TestDecode, CTest): pass

Misc/NEWS

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,9 @@ Core and Builtins
6262
Library
6363
-------
6464

65+
- Issue #19307: Improve error message for json.load(s) while passing objects
66+
of the wrong type.
67+
6568
- Issue #16038: CVE-2013-1752: ftplib: Limit amount of data read by
6669
limiting the call to readline(). Original patch by Michał
6770
Jastrzębski and Giampaolo Rodola.

0 commit comments

Comments
 (0)