Rob*_*rax 0 python json python-3.x
我正在尝试转换:
response data = {'policy': b'eyJleHBpcmF0a', 'signature': b'TdXjfAp'}
Run Code Online (Sandbox Code Playgroud)
到json:
jsonified = json.dumps( response_data )
Run Code Online (Sandbox Code Playgroud)
但它会导致错误消息:
TypeError:'bytes'类型的对象不是JSON可序列化的
进行正确转换的正确方法是什么?
预期结果
jsonified = {"policy": "eyJleHBpcmF0a", "signature": "TdXjfAp"}
Run Code Online (Sandbox Code Playgroud)
您可以为无法开箱即用的类型编写自己的编码器:
import json
class MyEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, (bytes, bytearray)):
return obj.decode("ASCII") # <- or any other encoding of your choice
# Let the base class default method raise the TypeError
return json.JSONEncoder.default(self, obj)
data = {'policy': b'eyJleHBpcmF0a', 'signature': b'TdXjfAp'}
jsonified = json.dumps( data, cls=MyEncoder )
print(jsonified)
# {"policy": "eyJleHBpcmF0a", "signature": "TdXjfAp"}
Run Code Online (Sandbox Code Playgroud)
这种方法可以很容易地扩展到支持其他类型,例如das datetime.
只需确保在函数末尾以str/int/float/...或任何其他可序列化类型结束.
正如@Tomalak指出的那样,你也可以使用base64编码而不是ASCII编码来确保你支持控制字符.