为什么当我传递 Powershell 变量时 jq 不编译?

时间:2021-05-21 11:48:40

标签: json powershell jq

受解决方案 here 的启发,如果 components.schemas 中未找到任何 JSON 条目,我想从 $paths 中删除它

这是我的带有 jq 的 Powershell 脚本:

$paths = jq '.. |.\"$ref\"? | select(. != null)' $srcJson
jq '.components.schemas |= with_entries( select( .key as $key | any(${paths}[]; index($key) )))' $srcJson | Out-File $destinationJson -Encoding UTF8

这是更改前的示例 JSON 文件:https://codebeautify.org/online-json-editor/cbc78213

然后这是我运行上面的 Powershell 脚本后的预期 JSON 文件:https://codebeautify.org/online-json-editor/cb8c4b2b

请注意,BadSchemas 已从 components.schemas 中删除

当我在 PowerShell 中运行代码时,我收到以下错误消息:

<块引用>

jq:错误:语法错误,意外的“{”,需要 IDENT 或 loc(Windows cmd shell 引用问题?),第 1 行: .components.schemas |= with_entries( select( .key as $key | any(${paths}[]; index($key) )))

谁能告诉我我做错了什么?

谢谢

1 个答案:

答案 0 :(得分:3)

Powershell doesn't expand variables 在单引号字符串中。如果您希望 ${paths} 被 Powershell 扩展,则需要使用双引号。

但是,通常这不是将变量传递给 jq 的最佳方式。最好使用 --arg and --argjson 分别将字符串和 json 值作为 jq 变量传入。

我没有 Windows 机器来测试这个,但你应该可以做这样的事情:

$paths = jq '.. |.\"$ref\"? | select(. != null)' $srcJson | ConvertTo-Json
jq --argjson paths "$paths" '.components.schemas |= with_entries( select( .key as $key | any($paths[]; index($key) )))' $srcJson | Out-File $destinationJson -Encoding UTF8