json - 如果任何嵌套值与设定值匹配,则打印键
问题描述
这最好用预期的输入和输出来解释。
鉴于此输入:
{
"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_id
s 都to_compute
与我的 input 匹配asset_id
。
到目前为止,我还没有看到任何将嵌套访问与任何测试 / if else 结合起来的 jq 示例。
解决方案
该任务可以在不使用环境变量的情况下完成,例如
< 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
推荐阅读
- java - 在 MYSQL AND 条件中使用 Java 谓词
- amazon-web-services - AWS SDK 如何在不指定凭证的情况下知道凭证?
- java - 为什么我的队列大小总是为零?调用插入时它应该增加
- swift - 更新 ObservableObject 后使视图不重绘
- ios - BezierPath 未在按钮点击时显示 - CGContextSetStrokeColorWithColor:无效上下文 0x0
- sql - SQL Pivot 表的一半
- javascript - 如何使用存储圆形图形元素的容器 [pixijs]
- spring-batch - 当有多个模式时,spring batch PatternMatchingCompositeTokenizer
- haskell - 使用 Haskell 中的函数更新记录中的字段
- java - Spring 数据查询图
非唯一结果