繁体   English   中英

在 BASH 文件/SHELL 脚本中使用 curl 请求发送 JSON:JSON_PARSING_ERROR:意外字符 (')

[英]Sending JSON with curl request in BASH File / SHELL script: JSON_PARSING_ERROR: Unexpected character (')

我查看了以下问题,因为我在插入 JSON 的字符串时遇到了问题,但仍然遇到了问题。

这是代码:(抱歉水平滚动)

JSON_DATA=\''{"notification": {"title": "'"$TITLE"'", "body": "'"$BODY"'", "sound": "'"${SOUND}"'"}, "to": "'"$DEVICE_ID"'"}'\'

这会返回一个结构良好的 JSON(以字符串形式)。

'{"notification": {"title": "random test", "body": "here is big body", "sound": "default"}, "to": "ejKgihBpSt4:APA91bGBl"}'

然后当我触发我的 CURL 时:

curl -H "Content-type: application/json" -H "Authorization:key=$FIREBASE_SERVER_KEY" -X POST -d "$JSON_DATA" https://fcm.googleapis.com/fcm/send

我收到以下错误: JSON_PARSING_ERROR: Unexpected character (') at position 0.

如果我将 ${JSON_DATA} 放在双引号之外,则会出现以下错误:

curl: (3) [globbing] unmatched brace in column 1
curl: (6) Could not resolve host: "random
curl: (6) Could not resolve host: test",
curl: (6) Could not resolve host: "body"
curl: (6) Could not resolve host: "here
curl: (6) Could not resolve host: is
curl: (6) Could not resolve host: big
curl: (6) Could not resolve host: body",
curl: (6) Could not resolve host: "sound"
curl: (3) [globbing] unmatched close brace/bracket in column 10
curl: (6) Could not resolve host: "to"
curl: (3) [globbing] unmatched close brace/bracket in column 24
JSON_PARSING_ERROR: Unexpected character (') at position 0.

去掉字符串周围的\\' 它不需要并且在 JSON 中无效。

JSON_DATA='{"notification": {"title": "'"$TITLE"'", "body": "'"$BODY"'", "sound": "'"${SOUND}"'"}, "to": "'"$DEVICE_ID"'"}'

请注意,如果任何变量包含双引号、换行符或其他必须在 JSON 中转义的特殊字符,这将产生不正确的结果。 最好安装jq实用程序并使用它为您创建 JSON。 有关示例,请参阅jq 和 bash:从变量生成 JSON 数组

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM