如何正确接收 Pubsub JSON 数据?
Posted
技术标签:
【中文标题】如何正确接收 Pubsub JSON 数据?【英文标题】:How to correctly receive Pubsub JSON data? 【发布时间】:2021-11-11 06:06:00 【问题描述】:我有一个带有云功能的 GCP 管道设置,可以接收 PubSub 消息。问题是每次我向云函数发布消息(一个 json 字符串)时,收到的消息与预期的有所不同。以下是我的代码:
import base64
def myfunc(event, context):
#receive pusub data
if 'data' in event:
payload = base64.b64decode(event['data']).decode('utf-8')
else:
payload = 'No Data'
payloadLocal ="considerIp":False,"wifiAccessPoints":[
"macAddress":"44:48:c1:a6:f3:d0",
"signalStrength":-54,
"signalToNoiseRatio":0,
"channel":11,
"age":0,
"macAddress":"9c:1c:12:b0:45:f1",
"signalStrength":-43,
"signalToNoiseRatio":0,
"channel":11,
"age":0,
"macAddress":"20:a6:cd:33:6c:f4",
"signalStrength":-32,
"signalToNoiseRatio":0,
"channel":11,
"age":0]
#Compare the received payload from pubsub with the local payload
#I expect to the same payload as payloadlocal
if payloadLocal == payload:
print("Payload same")
else:
print("Payload different")
我使用 pubsub 发布的消息是:
"considerIp":False,"wifiAccessPoints":[
"macAddress":"44:48:c1:a6:f3:d0",
"signalStrength":-54,
"signalToNoiseRatio":0,
"channel":11,
"age":0,
"macAddress":"9c:1c:12:b0:45:f1",
"signalStrength":-43,
"signalToNoiseRatio":0,
"channel":11,
"age":0,
"macAddress":"20:a6:cd:33:6c:f4",
"signalStrength":-32,
"signalToNoiseRatio":0,
"channel":11,
"age":0]
但是当我将 payloadlocal 与从 pubsub 消息接收到的有效负载进行比较时,它是不同的。我缺少一些愚蠢的东西。请任何人指出它。谢谢
编辑: 经过多次尝试,我找到了解决方案:
payload = base64.b64decode(event['data'])
dict_str = payload.decode("UTF-8")
payload = ast.literal_eval(dict_str)
我确信有更好的解决方案,但这对我有用。
【问题讨论】:
【参考方案1】:您正在将有效负载作为字符串加载并检查它是否等于字典。
以这种方式加载您的消息
payload = json.loads(base64.b64decode(event['data']).decode('utf-8'))
json.loads
转换字典中的字符串,如果它是一个有效的字典。
【讨论】:
感谢您的回复。但我现在收到以下错误“在 raw_decode raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 15 (char 14)" 编辑您的问题并打印事件内容['data']以上是关于如何正确接收 Pubsub JSON 数据?的主要内容,如果未能解决你的问题,请参考以下文章
如何使用当前的 pubsub 订阅者从 google Pub/Sub 系统获取消息
Firebase Emulator Cloud Functions + PubSub 订阅生产主题