其中包含需要转义的字符

其中包含需要转义的字符

本文介绍了如何发布带有curl的json字符串,其中包含需要转义的字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用了一个Shell脚本来将内容发布到嘻哈频道。在我尝试发送包含需要转义的字符的消息之前,它正常工作。我这样运行命令(注意那里的多余反斜杠会引起问题)

I've got a shell script I've been using to post stuff to a hipchat channel. It works ok until I try and send a message that has characters that need escaping. I run the command like so (note the extra backslash in there to cause a problem)

/usr/local/bin/hipchatmsg.sh "my great message here \ " red

bash脚本中的代码(hipchatmsg。 sh)这很重要:

And my code in my bash script (hipchatmsg.sh) that matters is this:

# 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

如果我尝试用任何需要转义的字符运行上述命令,我将得到如下错误:

If I try and run the command above with any characters that need escaping, I will get an error like this:

{
    "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"
    }
}

我在这里发现了类似的东西,最好的建议是尝试使用--data-urlencode发送curl帖子,所以我这样尝试:

I found something kind of similar on here where the best advice was to try sending the curl post with --data-urlencode, so I tried like this:

/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 &

但这没有效果。

我在这里缺少什么?

推荐答案

最简单的方法是使用生成JSON;

The easiest thing to do is use a program like jq to generate the JSON; it will take care of escaping what needs to be escaped.

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 &

@-的自变量$ c> -d 告诉 curl jq 通过管道。 jq -arg 选项使过滤器可以使用JSON编码的字符串,这只是一个JSON对象表达式

The argument @- to -d tells curl to read from standard input, which is supplied from jq via the pipe. The --arg options to jq make available JSON-encoded strings to the filter, which is simply a JSON object expression.

这篇关于如何发布带有curl的json字符串,其中包含需要转义的字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 23:46