【问题标题】:Why jq does not compile when I pass a Powershell variable?为什么当我传递 Powershell 变量时 jq 无法编译?
【发布时间】:2021-08-10 15:30:10
【问题描述】:

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

这是我的带有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: error: syntax error, unexpected '{', expecting IDENT or loc (Windows cmd shell quoting issues?) at , line 1: .components.schemas |= with_entries( select( .key as $key | any(${paths}[]; index($key) )))

谁能告诉我我哪里做错了?

谢谢

【问题讨论】:

  • $ref 是否设置了一些东西?第一行对我来说是空白的。什么是示例 json?我知道双引号需要反斜杠。
  • @js2010 这是带有 jq 命令的 JSON 截图 jqplay.org/s/kNkA2aDWPC
  • 哦,物业的名字字面意思是$ref?这很奇怪。
  • @js2010,$ref由openapi生成器自动生成

标签: json powershell jq


【解决方案1】:

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

【讨论】:

  • 我得到了invalid JSON text passed to --argjson,除非我先通过管道将 $paths 传递给 convertto-json。 $paths 不必双引号。
  • 请随时使用正确的命令行对此答案进行修改,否则我会在使用 Windows 机器时更新它。
猜你喜欢
  • 2020-05-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-30
  • 1970-01-01
  • 2012-06-19
  • 2023-03-11
  • 2015-01-25
相关资源
最近更新 更多