如何转义`jq`中的单引号
how to escape single quote in `jq`
我正在尝试使用 jq
格式化 json 字符串,预期输出如下:
[
{
"command": [
"printf 'this is a text'"
]
}
]
但是,我无法让它对单引号 (') 起作用,例如$ jq -n '[{"command": ["printf 'this is a text'"]}]'
给我一个编译错误。
我也考虑过转义所有双引号,例如jq -n "[{\"command\": [\"printf 'this is a text'\"]}]"
,这很好,但是 json 字符串是从函数传入的,我可以先用 \"
替换所有双引号,然后用 运行 jq 命令替换所有双引号,但它不是很优雅。
有没有更好的方法来处理 json 字符串中的单引号?
这里有四种应与 bash 或 bash-like shell 一起使用的备选方案。它们也可以适用于其他 shell。
jq -n $'[{"command": ["printf \'this is a text\'"]}]'
cat << EOF | jq .
[{"command": ["printf 'this is a text'"]}]
EOF
jq --arg cmd "printf 'this is a text'" -n '[{command: [ $cmd ]}]'
VAR="[{\"command\": [\"printf 'this is a text'\"]}]"
jq -n --argjson var "$VAR" '$var'
另见 How to escape single quotes within single quoted strings
我正在尝试使用 jq
格式化 json 字符串,预期输出如下:
[
{
"command": [
"printf 'this is a text'"
]
}
]
但是,我无法让它对单引号 (') 起作用,例如$ jq -n '[{"command": ["printf 'this is a text'"]}]'
给我一个编译错误。
我也考虑过转义所有双引号,例如jq -n "[{\"command\": [\"printf 'this is a text'\"]}]"
,这很好,但是 json 字符串是从函数传入的,我可以先用 \"
替换所有双引号,然后用 运行 jq 命令替换所有双引号,但它不是很优雅。
有没有更好的方法来处理 json 字符串中的单引号?
这里有四种应与 bash 或 bash-like shell 一起使用的备选方案。它们也可以适用于其他 shell。
jq -n $'[{"command": ["printf \'this is a text\'"]}]'
cat << EOF | jq .
[{"command": ["printf 'this is a text'"]}]
EOF
jq --arg cmd "printf 'this is a text'" -n '[{command: [ $cmd ]}]'
VAR="[{\"command\": [\"printf 'this is a text'\"]}]"
jq -n --argjson var "$VAR" '$var'
另见 How to escape single quotes within single quoted strings