json - 在 BASH 文件/SHELL 脚本中发送带有 curl 请求的 JSON: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: make JSON array from variable。
推荐阅读
- sql - Postgresql:如何从多个值的映射中进行选择
- macos - 在 MacOS 10.15 上安装 AWS EB CLI 时出现此错误“无法解压缩数据;zlib 不可用”
- excel - 对countif vba中的所有变量使用输入框
- clickhouse - 如何在 INTO OUTFILE 子句中指定本地目录?
- xamarin - 更改控件模板时如何防止重新加载 xamarin 地图?
- php - wordpress 登录功能无法使用 php
- python - 使用 cumtrapz 将加速度转换为位移
- android - 如何通过单击返回按钮发送数据?
- c++ - ioctl(tcpCnx->get_fd(), I_SRDOPT, RMSGN) coomand 在 LINUX RH7.4 上不起作用
- python - tensorflow 2胶囊网络实现重塑不起作用