如何转义`jq`中的单引号

Che*_*Xie 8 shell formatting json quotation-marks jq

我正在尝试使用预期输出来格式化 json 字符串,jq如下所示:

[
  {
    "command": [
      "printf 'this is a text'"
    ]
  }
]
Run Code Online (Sandbox Code Playgroud)

但是,我无法让它适用于单引号('),例如$ jq -n '[{"command": ["printf 'this is a text'"]}]'给我一个编译错误。

我还考虑过转义所有双引号,例如jq -n "[{\"command\": [\"printf 'this is a text'\"]}]",这很好,但是 json 字符串是从函数传入的,我可以\"先替换所有双引号,然后运行 ​​jq 命令,但这不是很优雅。

有没有更好的方法来处理 json 字符串中的单引号?

pea*_*eak 10

这里有四种可以与 bash 或类 bash shell 一起使用的替代方案。它们也可以适用于其他 shell。

jq -n $'[{"command": ["printf \'this is a text\'"]}]'
Run Code Online (Sandbox Code Playgroud)
cat << EOF | jq .
[{"command": ["printf 'this is a text'"]}]
EOF
Run Code Online (Sandbox Code Playgroud)
jq --arg cmd "printf 'this is a text'" -n '[{command: [ $cmd ]}]'
Run Code Online (Sandbox Code Playgroud)
VAR="[{\"command\": [\"printf 'this is a text'\"]}]"
jq -n --argjson var "$VAR" '$var'
Run Code Online (Sandbox Code Playgroud)

另请参阅如何转义单引号字符串中的单引号