Data which I'm receiving is bytes therefore I need temporary file-like container. To my best knowledge BytesIO is file-like object, but json.load() doesn't work on it:
In [1]: import json
...: from io import BytesIO, TextIOWrapper
In [2]: d, b = dict(a=1, b=2), BytesIO()
In [3]: b.write(json.dumps(d).encode())
Out[3]: 16
In [4]: b.seek(0)
Out[4]: 0
In [5]: b.read()
Out[5]: b'{"a": 1, "b": 2}'
In [6]: b.seek(0)
Out[6]: 0
In [7]: json.load(b)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-7-233ac51d2711> in <module>()
----> 1 json.load(b)
/usr/lib/python3.5/json/__init__.py in load(fp, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, **kw)
266 cls=cls, object_hook=object_hook,
267 parse_float=parse_float, parse_int=parse_int,
--> 268 parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)
269
270
/usr/lib/python3.5/json/__init__.py in loads(s, encoding, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, **kw)
310 if not isinstance(s, str):
311 raise TypeError('the JSON object must be str, not {!r}'.format(
--> 312 s.__class__.__name__))
313 if s.startswith(u'\ufeff'):
314 raise JSONDecodeError("Unexpected UTF-8 BOM (decode using utf-8-sig)",
TypeError: the JSON object must be str, not 'bytes'
One method that works:
In [8]: json.loads(b.getvalue().decode())
Out[8]: {'a': 1, 'b': 2}
Another one, presumably more efficient?
In [10]: b.seek(0)
Out[10]: 0
In [11]: json.load(TextIOWrapper(b, encoding='utf-8'))
Out[11]: {'a': 1, 'b': 2}
Do I have more (better) alternatives? If no, which one of the above methods should be preferred?