Python 如何在 JSON 中编码字节?json.dumps() 抛出 TypeError
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40000495/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to encode bytes in JSON? json.dumps() throwing a TypeError
提问by Fanta
I am trying to encode a dictionary containing a string of bytes with json
, and getting a is not JSON serializable error
.
我正在尝试对包含一串字节的字典进行编码json
,并得到一个is not JSON serializable error
.
Sample code:
示例代码:
import base64
import json
data={}
encoded = base64.encodebytes(b'data to be encoded')
data['bytes']=encoded
print(json.dumps(data))
The error I receive:
我收到的错误:
TypeError: b'ZGF0YSB0byBiZSBlbmNvZGVk\n' is not JSON serializable
How can I correctly encode my dictionary containing bytes with JSON?
如何使用 JSON 正确编码包含字节的字典?
回答by Martijn Pieters
The JSON format only supports unicode strings. Since Base64 encodes bytes to ASCII-only bytes, you can use that codec to decode the data:
JSON 格式仅支持unicode 字符串。由于 Base64 将字节编码为纯 ASCII 字节,您可以使用该编解码器来解码数据:
encoded = base64.encodestring(b'data to be encoded')
data['bytes'] = encoded.decode('ascii')