如何在JSON中编码字节? json.dumps()引发TypeError [英] How to encode bytes in JSON? json.dumps() throwing a TypeError
本文介绍了如何在JSON中编码字节? json.dumps()引发TypeError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用json
对包含字节字符串的字典进行编码,并得到is not JSON serializable error
.
I am trying to encode a dictionary containing a string of bytes with json
, and getting a is not JSON serializable error
.
示例代码:
import base64
import json
data={}
encoded = base64.encodebytes(b'data to be encoded')
data['bytes']=encoded
print(json.dumps(data))
我收到的错误:
TypeError: b'ZGF0YSB0byBiZSBlbmNvZGVk\n' is not JSON serializable
如何使用JSON正确编码包含字节的字典?
How can I correctly encode my dictionary containing bytes with JSON?
推荐答案
JSON格式仅支持 unicode字符串.由于Base64将字节编码为仅ASCII字节,因此您可以使用该编解码器解码数据:
The JSON format only supports unicode strings. Since Base64 encodes bytes to ASCII-only bytes, you can use that codec to decode the data:
encoded = base64.encodestring(b'data to be encoded')
data['bytes'] = encoded.decode('ascii')
这篇关于如何在JSON中编码字节? json.dumps()引发TypeError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文