json - 如何在 `jq` 中转义单引号

标签 json shell formatting jq quotation-marks

我正在尝试使用 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/

相关文章:

php - mysql 从 json 编码字段中选择指定的 key_name 和 key_value

java - 如何获取 Youtube Api Json 响应

bash - Unix Bash AIX - 从一个目录查找文件,但不在另一个目录中查找文件

python - 从元组列表创建格式化表

php - Guzzle 发布带有身份验证的请求

json - Freebase:使用 "namespace-prefix key"Json 对象

linux - 与 linux shell 有关的参数和选项之间的区别

linux - 如何捕获从 shell 脚本抛出的错误并将其显示在 groovy 中?

android - Eclipse 烦人的默认格式

formatting - 在 LaTeX 中排版 MLA 风格的大学论文最直接的方法是什么?