根据消费者调查文档,questions[].images[].data
字段采用字节数据类型。在
我使用python3来实现,但是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
,但没有这个部分的例子。在
谢谢
您需要使用web安全/URL安全编码。下面是Python中有关这样做的一些文档:https://pymotw.com/2/base64/#url-safe-variations
如果你的话,这看起来像
ETA:在Python 3中,API希望图像数据类型为^{cd1>},因此可以序列化JSON,但是^{cd2>}方法以UTF-8^{cd3>}的形式返回数据。您可以通过将字节转换为Unicode来修复此问题:
^{pr2}$相关问题 更多 >
编程相关推荐