1

根据消费者调查文档,该questions[].images[].data字段采用字节数据类型。

我正在使用 Python 3 来实现,但是 API 给出了类似Invalid ByteString或字节类型的错误is not JSON serializable.

我正在使用以下代码:

    import base64
    import urllib
    url = 'http://example.com/image.png'
    raw_img = urllib.request.urlopen(url).read()

    # is not JSON serializable due to json serializer not being able to serialize raw bytes
    img_data = raw_img

    # next errors: Invalid ByteString, when tried with base64 encoding as followings:
    img_data = base64.b64encode(raw_img)
    # Also tried decoding it to UTF.8 `.decode('utf-8')`

img_data是发送到 API 的 JSON 有效负载的一部分。

我错过了什么吗?处理问题图像数据上传的正确方法是什么?我调查过,https://github.com/google/consumer-surveys/tree/master/python/src但没有这部分的例子。

谢谢

4

1 回答 1

2

您需要使用网络安全/URL 安全编码。这是一些关于在 Python 中执行此操作的文档:https ://pymotw.com/2/base64/#url-safe-variations

在你的情况下,这看起来像

img_data = base64.urlsafe_b64encode(raw_img)

ETA:在 Python 3 中,API 期望图像数据的类型str为 JSON 序列化,但该base64.urlsafe_b64encode方法以 UTF-8 的形式返回数据bytes。您可以通过将字节转换为 Unicode 来解决此问题:

img_data = base64.urlsafe_b64encode(raw_img)
img_data = img_data.decode('utf-8')
于 2016-08-16T19:13:09.780 回答