Skip to content

bpo-30193: Allow to load buffer objects with json.loads() #14977

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 2 commits 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
26 changes: 15 additions & 11 deletions Lib/json/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -242,12 +242,13 @@ def dumps(obj, *, skipkeys=False, ensure_ascii=True, check_circular=True,


def detect_encoding(b):
bstartswith = b.startswith
if bstartswith((codecs.BOM_UTF32_BE, codecs.BOM_UTF32_LE)):
return 'utf-32'
if bstartswith((codecs.BOM_UTF16_BE, codecs.BOM_UTF16_LE)):
return 'utf-16'
if bstartswith(codecs.BOM_UTF8):
for prefix in (codecs.BOM_UTF32_BE, codecs.BOM_UTF32_LE):
if b[:len(prefix)] == prefix:
return 'utf-32'
for prefix in (codecs.BOM_UTF16_BE, codecs.BOM_UTF16_LE):
if b[:len(prefix)] == prefix:
return 'utf-16'
if b[:len(codecs.BOM_UTF8)] == codecs.BOM_UTF8:
return 'utf-8-sig'

if len(b) >= 4:
Expand Down Expand Up @@ -337,11 +338,14 @@ def loads(s, *, cls=None, object_hook=None, parse_float=None,
raise JSONDecodeError("Unexpected UTF-8 BOM (decode using utf-8-sig)",
s, 0)
else:
if not isinstance(s, (bytes, bytearray)):
raise TypeError(f'the JSON object must be str, bytes or bytearray, '
f'not {s.__class__.__name__}')
s = s.decode(detect_encoding(s), 'surrogatepass')

if not isinstance(s, (bytes, bytearray, memoryview)):
try:
s = memoryview(s)
except TypeError:
raise TypeError('the JSON object must be str, bytes or '
'bytearray or memoryview compatible object, '
Comment on lines +345 to +346
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
raise TypeError('the JSON object must be str, bytes or '
'bytearray or memoryview compatible object, '
raise TypeError('the JSON object must be str, bytes, '
'bytearray, or a memoryview-compatible object, '

'not {!r}'.format(s.__class__.__name__))
s = str(s, detect_encoding(s), 'surrogatepass')
if "encoding" in kw:
import warnings
warnings.warn(
Expand Down
10 changes: 10 additions & 0 deletions Lib/test/test_json/test_decode.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import array
import decimal
from io import StringIO
from collections import OrderedDict
Expand All @@ -20,6 +21,15 @@ def test_empty_objects(self):
self.assertEqual(self.loads('[]'), [])
self.assertEqual(self.loads('""'), "")

def test_memoryview(self):
data = memoryview(b'{"key": "val"}')
Copy link
Member

Choose a reason for hiding this comment

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

Use different encodings with BOM. Test also with memoryview(...).cast('H').

self.assertEqual(self.loads(data), {"key": "val"})

def test_buffer(self):
data = array.array('B')
Copy link
Member

Choose a reason for hiding this comment

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

Use different encodings with BOM. Test also with array.array('H').

data.frombytes(b'{"key": "val"}')
self.assertEqual(self.loads(data), {"key": "val"})

def test_object_pairs_hook(self):
s = '{"xkd":1, "kcw":2, "art":3, "hxm":4, "qrt":5, "pad":6, "hoy":7}'
p = [("xkd", 1), ("kcw", 2), ("art", 3), ("hxm", 4),
Expand Down
1 change: 1 addition & 0 deletions Misc/ACKS
Original file line number Diff line number Diff line change
Expand Up @@ -841,6 +841,7 @@ Sanyam Khurana
Mads Kiilerich
Jason Killen
Jan Kim
Nikolay Kim
Taek Joo Kim
Sam Kimbrel
Tomohiko Kinebuchi
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Allow to load buffer objects with `json.loads()`. Patch by Nikolay Kim
<[email protected]>.