【问题标题】:Json dumping bytes fails in Python 3Python 3 中的 JSON 转储字节失败
【发布时间】:2016-02-21 01:16:54
【问题描述】:

我在发布请求中发送二进制数据作为请求的一部分。我有一本看起来像这样的字典:

data = {"foo": "bar", "bar": b'foo'}

当我尝试json.dumps 这本词典时,我得到以下异常:

TypeError: b'foo' is not JSON serializable

这在 Python 2.7 中运行良好。我该怎么做才能对这些数据进行 json 编码?

【问题讨论】:

标签: python json python-3.x python-3.5


【解决方案1】:

在 Python 3 中,他们删除了 json 中的 byte 支持。 (来源:https://bugs.python.org/issue10976)。

一种可能的解决方法是:

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):

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)

【讨论】:

    【解决方案2】:

    使用 Json 模块,您不能转储字节。 一个合适的替代方法是使用简单 Json 模块。

    安装简单的 json:

    pip3 安装 simplejson

    代码:

    import simplejson as json
    data = {"foo": "bar", "bar": b"foo"}
    json.dumps(data)
    

    希望您现在不会收到错误消息!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-29
      • 2014-01-27
      相关资源
      最近更新 更多