首页 > 解决方案 > 如果任何嵌套值与设定值匹配,则打印键

问题描述

这最好用预期的输入和输出来解释。

鉴于此输入:

{
  "27852380038": {
    "compute_id": 34234234,
    "to_compute": [
      {
        "asset_id": 304221854,
        "new_scheme": "mynewscheme",
        "original_host": "oldscheme1234.location.com"
      },
      {
        "asset_id": 12123121,
        "new_scheme": "myotherscheme",
        "original_host": "olderscheme1234.location.com"
      }
    ]
  },
  "31352333022": {
    "compute_id": 43888877,
    "to_compute": [
      {
        "asset_id": 404221555,
        "new_scheme": "mynewscheme",
        "original_host": "oldscheme1234.location.com"
      },
      {
        "asset_id": 52123444,
        "new_scheme": "myotherscheme",
        "original_host": "olderscheme1234.location.com"
      }
    ]
  }
}

asset_id我正在搜索的 12123121,输出应该是:

27852380038

所以我想要顶级键,其中任何一个asset_ids 都to_compute与我的 input 匹配asset_id

到目前为止,我还没有看到任何将嵌套访问与任何测试 / if else 结合起来的 jq 示例。

标签: jsonjq

解决方案


该任务可以在不使用环境变量的情况下完成,例如

< input.json jq -r --argjson ASSET_ID 12123121 '
  to_entries[]
  | {key, asset_id: .value.to_compute[].asset_id}
  | select(.asset_id==$ASSET_ID)
  | .key'

或更有效地,使用过滤器:

to_entries[]
| select( any( .value.to_compute[]; .asset_id==$ASSET_ID) )
| .key

推荐阅读