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 ' .\+'`

将MSG设置为:

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.

推荐答案

好的,我知道该怎么做了.Bash在本机上支持这一点,尽管一如既往,语法并不是很容易猜测!

Essentially ${string//substring/replacement} returns what you'd image, so you can use

MSG=${MSG//\'/\\\'}

才能做到这一点.下一个问题是第一个正则表达式不再工作,但是可以用

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.

Json相关问答推荐

筛选JSON数组以使用Jolt仅保留具有最新日期/时间的条目

创建Json嵌套文件 struct

JQ-JSON将键转换为对象

在Zig中解析JSON失败

简单条形图和有序分类中条形图的 colored颜色 梯度

用巨大的值更新SQL Server中的nvarchar(max)

删除 JOLT 中的方括号

如何使用Powershell查找所有包含特定键值对的JSON对象并迭代所有对象?

Bicep脚本中如何设置弹性池的维护窗口?

使用本地 JSON api react TS Axios

jq json - 按键名 Select

golang递归json来构造?

我无法在 Go - Gin 中解析日期/时间

使用基本身份验证通过 CURL 发布 JSON

什么是类型和类型令牌?

Spring MVC:不反序列化 JSON 请求正文

如何将 Swift 对象转换为字典

如何按键查找特定的 JSON 值?

如何使用 Serde 反序列化带有自定义函数的可选字段?

确保数组中的项目属性在 Json Schema 中是唯一的?