py3: Allow serializing utf-8 bytestrings to JSON

This matches behavior of py2
This commit is contained in:
Kovid Goyal 2019-03-16 14:06:15 +05:30
parent b23ba9dbdb
commit dcb128eb8b
No known key found for this signature in database
GPG Key ID: 06BC317B515ACE7C
2 changed files with 4 additions and 0 deletions

View File

@ -203,6 +203,8 @@ def to_json(obj):
'__value__': isoformat(obj, as_utc=True)} '__value__': isoformat(obj, as_utc=True)}
if isinstance(obj, (set, frozenset)): if isinstance(obj, (set, frozenset)):
return {'__class__': 'set', '__value__': tuple(obj)} return {'__class__': 'set', '__value__': tuple(obj)}
if isinstance(obj, bytes):
return obj.decode('utf-8')
if hasattr(obj, 'toBase64'): # QByteArray if hasattr(obj, 'toBase64'): # QByteArray
return {'__class__': 'bytearray', return {'__class__': 'bytearray',
'__value__': bytes(obj.toBase64()).decode('ascii')} '__value__': bytes(obj.toBase64()).decode('ascii')}

View File

@ -43,6 +43,8 @@ def create_encoder(for_json=False):
return encoded(3, fm_as_dict(obj), ExtType) return encoded(3, fm_as_dict(obj), ExtType)
elif isinstance(obj, Tag): elif isinstance(obj, Tag):
return encoded(4, obj.as_dict(), ExtType) return encoded(4, obj.as_dict(), ExtType)
if for_json and isinstance(obj, bytes):
return obj.decode('utf-8')
raise TypeError('Cannot serialize objects of type {}'.format(type(obj))) raise TypeError('Cannot serialize objects of type {}'.format(type(obj)))
return encoder return encoder