Skip to main content
 首页 » 编程设计

python之将列表转换为谷歌发布/订阅的字节串

2025年01月19日9myhome

我在从 python 客户端向谷歌云发布/订阅服务发布消息时遇到问题。

我有基于 rest 的公共(public) API,它返回 JSON 数据。返回的数据是列表中的字典形式。

我已将字典中的值提取到一个列表中,并使用 bytes() 转换为字节串,但它仍然在下面抛出异常。

['EB', 'Pulaski', '2018-03-06 21:50:18.0', '0.5', '41.7930671862', '41.793140551', '-87.7136071496', 'W', '中央公园'、'-1'、'1'、'-87.7231602513'、'55th']

response = requests.get("https://data.cityofchicago.org/resource/8v9j-bter.json") 
traffic = response.json() 
 
 
result_list = [] 
for d in traffic: 
  result_list.append([v for k, v in d.items()]) 
 
for x in result_list: 
  print(x) 
  publisher.publish(topic_path, data = bytes(x)) 

请您参考如下方法:

根据此处的 Python 示例,看起来您应该使用 x.encode('utf-8') 而不是 bytes(x) 来转换为字节串:https://cloud.google.com/pubsub/docs/publisher#publish-messages-to-a-topic