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

问题描述

我正在尝试使用 2012.xlsx 2013.xlsx 2014.xlsx Name Alf 600.0 200.0 0.0 Elf 400.0 0.0 0.0 Tim 0.0 0.0 150.0 格式化json字符串,其预期输出如下:

jq

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

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

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

解决方法

这里有四个替代方法可以与bash或类似bash的外壳一起使用。它们也可以适用于其他外壳。

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