list - jq 根据列表中的值过滤 JSON 数组
问题描述
如果以下条件匹配,我想使用jq
返回值,即有一个匹配的元素RuleArn
.[].Conditions[].Values[]
app.fantastic.com
我的 JSON 数组:
[
{
"Conditions": [
{
"Field": "http-header",
"HttpHeaderConfig": {
"Values": [
"dark"
],
"HttpHeaderName": "Environment"
}
},
{
"Values": [
"app.fantastic.com"
],
"Field": "host-header",
"HostHeaderConfig": {
"Values": [
"app.fantastic.com"
]
}
}
],
"IsDefault": false,
"Priority": "3",
"RuleArn": "iwantthisvalue"
}
]
我试过这些:
| jq -r '.[] | select(.Conditions[].Values[]=="app.fantastic.com")'
和
| jq -r '.[] | select(.Conditions[].Values[] | has("app.fantastic.com"))'
我收到以下错误:
jq:错误(在:144):无法使用字符串“条件”索引数组
有了这个:
| jq '.[].Conditions[].Values | index ("app.fantastic.com") == 0 | .RuleArn'
这是我得到的错误:
jq:错误(在:47):无法使用字符串“RuleArn”索引布尔值
注意:我不想要使用--query
AWS cli 的解决方案,因为我--query
已经使用它来获取更小的 JSON 有效负载,我想使用jq
.
解决方案
您遇到的困难的根源是问题陈述不正确:.[].Conditions[].Values[]
与您的 JSON 不对应。
使用 jq 1.5 或更高版本,您可以使用以下过滤器:
.[]
| first(select(.Conditions | .. | objects
| select(has("Values") and
(.Values|index("app.fantastic.com")))))
| .RuleArn
由于 .Values 出现在多个位置,因此尚不清楚确切的要求是什么,但您可能还希望考虑:
.[]
| select(.Conditions[].Values? | index("app.fantastic.com"))
| .RuleArn
或(效率较低,但适用于 jq 1.4 或更高版本):
.[]
| select(.Conditions[].Values[]? == "app.fantastic.com")
| .RuleArn
推荐阅读
- regex - 在 Google 表格中使用正则表达式进行聚合
- git - 如何修复 Contiki 中的“致命:不是有效的对象名称 HEAD”错误?
- laravel - 如何在 chartjs 和 laravel 图表 consoletvs/chartsjs 中使用插件
- xml - 字段名称中的 FX 标记特殊字符
- java - 如何使用 OpenCSV 将 csv 导入 FX SimpleObjectProperties?
- java - Parallel Mergesort 基准测试 - 确定找到的阈值
- angular - 未捕获的类型错误:promise.fulfill 不是函数(与 Zone.js 冲突)(Angular 5)
- javascript - 更改 HTML 对象属性
- c# - 从控制器显示模态弹出 div
- asp.net-mvc - Visual Studio 2019 中的 MVC 不会像 2015 那样自动创建文件吗?