使用 PowerShell 在 JQ 中使用字符串文字

String literals in JQ using PowerShell

我无法让 JQ 字符串文字在 Powershell 中工作。 例如,这会在 Bash 中输出一个漂亮的 JSON 对象,但在 Powershell 中会失败:

PS C:\temp> jq --null-input '{"key":"val"}'

jq: error: val/0 is not defined at <top-level>, line 1:
{key:val}
jq: 1 compile error

起初我怀疑引用不正确,但 Write-Output '{"key":"val"}' 输出 {"key":"val"} 正如我所料。

我可以通过将我的 JQ 过滤器写入文件来解决这个问题。使用 .NET WriteAllText 确保文件被编码为没有 BOM 的 UTF-8。

PS C:\temp> [System.IO.File]::WriteAllText('basic.jq', '{"key":"val"}')
PS C:\temp> jq --null-input --from-file basic.jq
{
  "key": "val"
}

我正在寻找一种更灵活的方法来制作 JQ 过滤器的原型并将它们集成到 PowerShell 脚本中。

版本:JQ 1.6 for win64,PSVersion 5.1.18362.1171

Powershell 可能希望您转义 '..' 表达式中的双引号。尝试

jq --null-input '{ "key": \"val\" }'

或正下方,因为 jq 中的键名不需要显式引号

jq --null-input '{ key: \"val\" }'

来自 jq 手册 - Invoking jq

When using the Windows command shell (cmd.exe) it's best to use double quotes around your jq program when given on the command-line (instead of the -f program-file option), but then double-quotes in the jq program need backslash escaping.