JSON format only supports Unicode strings.
you can decode to string(which is Unicode by default in Python 3),be using
Error:
you can decode to string(which is Unicode by default in Python 3),be using
decode()
or decode('ascii')
as Base64 encodes bytes to ASCII-only bytes.Error:
>>> import base64 >>> import json >>> >>> place = base64.b64encode(open('foo.txt', "rb").read()) >>> place b'aGVsbG8gd29ybGQNCg0K' >>> type(place) <class 'bytes'> >>> d = {} >>> d['name'] = place >>> json.dumps(d) Traceback (most recent call last): File "<string>", line 428, in runcode File "<interactive input>", line 1, in <module> File "C:\Python37\lib\json\__init__.py", line 231, in dumps return _default_encoder.encode(obj) File "C:\Python37\lib\json\encoder.py", line 199, in encode chunks = self.iterencode(o, _one_shot=True) File "C:\Python37\lib\json\encoder.py", line 257, in iterencode return _iterencode(o, 0) File "C:\Python37\lib\json\encoder.py", line 179, in default raise TypeError(f'Object of type {o.__class__.__name__} ' TypeError: Object of type bytes is not JSON serializableFix:
>>> import base64 >>> import json >>> >>> place = base64.b64encode(open('foo.txt', "rb").read()).decode() # Or decode('ascii') >>> type(place) <class 'str'> >>> d = {} >>> d['name'] = place >>> json.dumps(d) '{"name": "aGVsbG8gd29ybGQNCg0K"}'