首页 > 解决方案 > 在 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.

标签: jsonbashshell

解决方案


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

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

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


推荐阅读