我有一个shell脚本,我一直用来发布到hipchat频道的东西.它工作正常,直到我尝试发送一个包含需要转义的字符的消息.我像这样运行命令(注意那里的额外反斜杠导致问题)
/usr/local/bin/hipchatmsg.sh "my great message here \ " red
Run Code Online (Sandbox Code Playgroud)
我的bash脚本(hipchatmsg.sh)中的代码重要的是:
# Make sure message is passed
if [ -z ${1+x} ]; then
echo "Provide a message to create the new notification"
exit 1
else
MESSAGE=$1
fi
// send locally via curl
/usr/bin/curl -H "Content-Type: application/json" \
-X POST \
-k \
-d "{\"color\": \"$COLOR\", \"message_format\": \"text\", \"message\": \"$MESSAGE\" }" \
$SERVER/v2/room/$ROOM_ID/notification?auth_token=$AUTH_TOKEN &
// $server and $room are defined earlier
exit 0
Run Code Online (Sandbox Code Playgroud)
如果我尝试使用任何需要转义的字符运行上面的命令,我将得到如下错误:
{
"error": {
"code": 400,
"message": "The request body cannot be parsed as valid JSON: Invalid \\X escape sequence u'\\\\': line 1 column 125 (char 124)",
"type": "Bad Request"
}
}
Run Code Online (Sandbox Code Playgroud)
我在这里找到了类似的东西,最好的建议是尝试使用--data-urlencode发送curl帖子,所以我试着这样:
/usr/bin/curl -H "Content-Type: application/json" \
-X POST \
-k \
-d --data-urlencode "{\"color\": \"$COLOR\", \"message_format\": \"text\", \"message\": \"$MESSAGE\" }" \
$SERVER/v2/room/$ROOM_ID/notification?auth_token=$AUTH_TOKEN &
Run Code Online (Sandbox Code Playgroud)
但这没有效果.
我在这里错过了什么?
che*_*ner 11
最简单的方法是使用像jq
生成JSON 的程序; 它会照顾逃避需要逃脱的东西.
jq -n --arg color "$COLOR" \
--arg message "$MESSAGE" \
'{color: $color, message_format: "text", message: $message}' |
/usr/bin/curl -H "Content-Type: application/json" \
-X POST \
-k \
-d@- \
$SERVER/v2/room/$ROOM_ID/notification?auth_token=$AUTH_TOKEN &
Run Code Online (Sandbox Code Playgroud)
的参数@-
,以-d
告诉curl
从标准输入,这是从提供给读jq
经由管道.为过滤器提供可用的JSON编码字符串的--arg
选项jq
,它只是一个JSON对象表达式.