在bash中转义字符(对于JSON) [英] Escaping characters in bash (for JSON)
问题描述
我正在使用git,然后将提交消息和其他位作为JSON负载发送到服务器。
目前我有:
MSG =`git log -n 1 --format = oneline | grep -o'.\ +'`
它将MSG设置为:
日历今天不能回去
然后
curl -i -X POST \
-H'接受:应用程序/ text'\
-H'Content-type:application / json'\
-d{'payload':{'message':'$ MSG'}}\
'https://example.com'
我的真正的JSON还有另外几个字段。 / p>
这个工作正常,但当然我有一个提交信息,如上面的一个撇号,JSON是无效的。
如何避免bash中需要的字符?我不熟悉语言,所以我不知道从哪里开始。将'
替换为 \'
将至少可以完成这项工作。
<确定方法可以找出做什么的div class =h2_lin>解决方案Bash本来就像预期一样支持,尽管一如以往,语法不是很可猜测!
本质上 $ {string // substring / replacement }
返回您想要的图像,因此您可以使用
MSG = $ {MSG // \'/ \\\'}
这样做。下一个问题是第一个正则表达式不再工作,但可以用
git log -n 1替换 - -pretty =格式:'%s'
最后,我甚至不需要逃脱他们。相反,我只是将所有的JSON交换到\\,那么你每天都会学到一些东西。
I'm using git, then posting the commit message and other bits as a JSON payload to a server.
Currently I have:
MSG=`git log -n 1 --format=oneline | grep -o ' .\+'`
which sets MSG to something like:
Calendar can't go back past today
then
curl -i -X POST \
-H 'Accept: application/text' \
-H 'Content-type: application/json' \
-d "{'payload': {'message': '$MSG'}}" \
'https://example.com'
My real JSON has another couple of fields.
This works fine, but of course when I have a commit message such as the one above with an apostrophe in it, the JSON is invalid.
How can I escape the characters required in bash? I'm not familiar with the language, so am not sure where to start. Replacing '
with \'
would do the job at minimum I suspect.
OK, found out what to do. Bash supports this natively as expected, though as always, the syntax isn't really very guessable!
Essentially ${string//substring/replacement}
returns what you'd image, so you can use
MSG=${MSG//\'/\\\'}
To do this. The next problem is that the first regex doesn't work anymore, but that can be replaced with
git log -n 1 --pretty=format:'%s'
In the end, I didn't even need to escape them. Instead, I just swapped all the ' in the JSON to \". Well, you learn something every day.
这篇关于在bash中转义字符(对于JSON)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!