使用PowerShell时,jq查询中应如何转义双引号


我需要执行一个包含双引号的jq查询。我用单引号包装了查询,所以双引号字符应该被解释为普通字符。不幸的是,jq对它们进行了修剪。我不明白我应该如何以及为什么逃避双引号字符。

示例:我有test.json文件:

{
"artifacts": [
{
"id": "foo",
"name": "Foo",
"version": "1.0",
"licenses": [
"GPL-1",
"GPL-2"
]
},
{
"id": "bar",
"name": "Bar",
"version": "3.0",
"licenses": [
"GPL-3",
"Apache 2.0"
]
},
{
"id": "ignored",
"name": "Ignored",
"version": "3.0",
"licenses": [
"Apache 2.0"
]
}
]
}

我想列出至少有一个GPL许可证的所有工件(nameversion(。结果应按name的字母顺序进行排序。处理它的查询如下:

[.artifacts[] | select(.licenses[] | startswith("GPL-"))] | unique_by(.id) | sort_by(.name) | .[] | "(.name) (.version)"

不幸的是,当我执行命令时,它失败了:

> cat .test.json | jq -r '[.artifacts[] | select(.licenses[] | startswith("GPL-"))] | unique_by(.id) | sort_by(.name) | .[] | "(.name) (.version)"'
jq: error: syntax error, unexpected ')' (Windows cmd shell quoting issues?) at <top-level>, line 1:
[.artifacts[] | select(.licenses[] | startswith(GPL-))] | unique_by(.id) | sort_by(.name) | .[] | (.name)
jq: error: syntax error, unexpected INVALID_CHARACTER (Windows cmd shell quoting issues?) at <top-level>, line 1:
[.artifacts[] | select(.licenses[] | startswith(GPL-))] | unique_by(.id) | sort_by(.name) | .[] | (.name)
jq: 2 compile errors

错误消息显示缺少双引号字符。我尝试了许多组合,最终找到了正确的配置:

> cat .test.json | jq -r '[.artifacts[] | select(.licenses[] | startswith(""GPL-""""))] | unique_by(.id) | sort_by(.name) | .[] | """(.name) (.version)""'
Bar 3.0
Foo 1.0

我不明白为什么我要两个,下一个四个,下三个,最后两个引号。

查询在Linux上运行良好:

$ cat ./test.json | jq -r '[.artifacts[] | select(.licenses[] | startswith("GPL-"))] | uniq
ue_by(.id) | sort_by(.name) | .[] | "(.name) (.version)"'
Bar 3.0
Foo 1.0

jq作者的建议是,当使用cmd时,在Windows上用双引号包装查询。接下来,双引号字符应该用斜杠转义(阅读Invoking jq(:

使用Windows命令行shell(cmd.exe(时,最好在命令行上提供的jq程序周围使用双引号(而不是-f程序文件选项(,但jq程序中的双引号需要反斜杠转义。

我用单引号&在带有PowerShell的Windows上用反斜杠转义双引号。它起作用:

> cat .test.json | jq -r '[.artifacts[] | select(.licenses[] | startswith("GPL-"))] | unique_by(.id) | sort_by(.name) | .[] | "(.name) (.version)"'
Bar 3.0
Foo 1.0

也可以使用双引号,但双引号字符必须转义两次,例如:

  • jq:""
  • PowerShell:"""

所需转换:"""

> cat .test.json | jq -r "[.artifacts[] | select(.licenses[] | startswith(""GPL-""))] | unique_by(.id) | sort_by(.name) | .[] | ""(.name) (.version)"""
Bar 3.0
Foo 1.0

正如本文中所描述的mklement0,由于PowerShell中的一个错误,需要额外的转义。

最新更新