Windows下用gcloud CLI发消息时Firebase PubSub函数JSON解析错误
问题
在Cloud Functions v2中配置账单PubSub监听器,使用Windows系统的gcloud CLI发送测试JSON消息时,遭遇JSON解析错误,错误信息如下:
Unable to parse Pub/Sub message data as JSON: Unexpected token b in JSON at position 1
排查发现函数接收的字符串双引号被移除,但通过Google Cloud Console测试时日志正常,切换v1版本CLI仍报错,推测是Windows版gcloud CLI的引号解析问题。
使用的发布命令:
gcloud pubsub topics publish billing --message '{"budgetDisplayName":"name-of-budget","alertThresholdExceeded":1,"costAmount":100.01,"costIntervalStart":"2019-01-01T00:00:00Z","budgetAmount":100,"budgetAmountType":"SPECIFIED_AMOUNT","currencyCode":"USD"}'
Cloud Functions代码:
import { onMessagePublished } from "firebase-functions/v2/pubsub"; import * as logger from "firebase-functions/logger"; exports.onBillingAlert = onMessagePublished( "projects/thrilling-tales/topics/billing", async (event) => { logger.debug("onBillingAlert"); logger.debug(event.data.message.json); } );
解决方案
问题根源是Windows的CMD/PowerShell对引号的处理逻辑与类Unix系统不同,直接用单引号包裹JSON会导致shell错误解析双引号,最终传递给PubSub的消息格式损坏。以下是几种可行的解决方法:
方法1:CMD环境下转义双引号
将JSON外层的单引号替换为双引号,同时内部的每个双引号前添加反斜杠转义:
gcloud pubsub topics publish billing --message "{\"budgetDisplayName\":\"name-of-budget\",\"alertThresholdExceeded\":1,\"costAmount\":100.01,\"costIntervalStart\":\"2019-01-01T00:00:00Z\",\"budgetAmount\":100,\"budgetAmountType\":\"SPECIFIED_AMOUNT\",\"currencyCode\":\"USD\"}"
方法2:PowerShell环境下使用Here-String
利用PowerShell的Here-String语法定义JSON消息,避免引号解析冲突:
$jsonContent = @" {"budgetDisplayName":"name-of-budget","alertThresholdExceeded":1,"costAmount":100.01,"costIntervalStart":"2019-01-01T00:00:00Z","budgetAmount":100,"budgetAmountType":"SPECIFIED_AMOUNT","currencyCode":"USD"} "@ gcloud pubsub topics publish billing --message $jsonContent
方法3:通过文件传递消息(最稳妥)
将JSON内容写入一个文件(比如billing-alert.json),然后使用--message-from-file参数发送:
# 先创建billing-alert.json文件,内容为目标JSON gcloud pubsub topics publish billing --message-from-file billing-alert.json
采用以上方法后,PubSub将收到格式正确的JSON消息,Cloud Functions可以正常解析。
内容的提问来源于stack exchange,提问作者salesp07
相关产品推荐
相关产品推荐

