Python 3中Json转储字节失败
我在post请求中发送二进制数据,作为请求的一部分。我有一本这样的字典:Python 3中Json转储字节失败,python,json,python-3.x,python-3.5,Python,Json,Python 3.x,Python 3.5,我在post请求中发送二进制数据,作为请求的一部分。我有一本这样的字典: data = {"foo": "bar", "bar": b'foo'} 当我尝试json.dumps此字典时,我得到以下异常: TypeError: b'foo' is not JSON serializable 这在Python2.7中运行良好。我该怎么做才能用json编码这些数据呢?在Python3中,他们删除了json中的byte支持。(来源:) 一种可能的解决方法是: import json data =
data = {"foo": "bar", "bar": b'foo'}
当我尝试json.dumps
此字典时,我得到以下异常:
TypeError: b'foo' is not JSON serializable
这在Python2.7中运行良好。我该怎么做才能用json编码这些数据呢?在Python3中,他们删除了
json
中的byte
支持。(来源:)
一种可能的解决方法是:
import json
data = {"foo": "bar", "bar": b"foo"}
# decode the `byte` into a unicode `str`
data["bar"] = data["bar"].decode("utf8")
# `data` now contains
#
# {'bar': 'foo', 'foo': 'bar'}
#
# `json_encoded_data` contains
#
# '{"bar": "foo", "foo": "bar"}'
#
json_encoded_data = json.dumps(data)
# `json_decoded_data` contains
#
# {'bar': 'foo', 'foo': 'bar'}
#
json_decoded_data = json.loads(data)
# `data` now contains
#
# {'bar': b'foo', 'foo': 'bar'}
#
data["bar"] = data["bar"].encode("utf8")
如果您没有使用<代码> JSON<代码>的约束,您可以考虑使用<代码> BSON(二进制JSON):
使用Json模块,您不能转储字节。 一个合适的替代方法是使用简单的Json模块 要安装简单json,请执行以下操作: pip3安装simplejson 代码: 希望你现在不会出错 可能重复的
import bson
data = {"foo": "bar", "bar": b"foo"}
# `bson_encoded_data` contains
#
# b'\x1f\x00\x00\x00\x05bar\x00\x03\x00\x00\x00\x00foo\x02foo\x00\x04\x00\x00\x00bar\x00\x00'
#
bson_encoded_data = bson.BSON.encode(data)
# `bson_decoded_data` contains
#
# {'bar': b'foo', 'foo': 'bar'}
#
bson_decoded_data = bson.BSON.decode(data)
import simplejson as json
data = {"foo": "bar", "bar": b"foo"}
json.dumps(data)