我正在尝试使用 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 的 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
关于json - 如何在 `jq` 中转义单引号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64601031/