首页 > 解决方案 > 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”索引布尔值

注意:我不想要使用--queryAWS cli 的解决方案,因为我--query已经使用它来获取更小的 JSON 有效负载,我想使用jq.

标签: listfilterjq

解决方案


您遇到的困难的根源是问题陈述不正确:.[].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

推荐阅读