【问题标题】:jq filter JSON array based on value in listjq 根据列表中的值过滤 JSON 数组
【发布时间】:2020-04-30 23:07:48
【问题描述】:

如果以下条件匹配,我想使用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):无法使用字符串“Conditions”索引数组

还有这个:

| jq '.[].Conditions[].Values | index ("app.fantastic.com") == 0 | .RuleArn'

这是我得到的错误:

jq: error (at :47): Cannot index boolean with string "RuleArn"

注意:我不想要使用 AWS cli 的 --query 的解决方案,因为我已经使用 --query 来获得更小的 JSON 有效负载,我想使用jq 进一步过滤它。

【问题讨论】:

    标签: list filter jq


    【解决方案1】:

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

    【讨论】:

    • 嘿,谢谢Peak,这个符号是什么意思? | .. | objects
    • 不幸的是,所有 3 个解决方案都给了我同样的错误 jq: error (at <stdin>:144): Cannot index array with string "Conditions"
    猜你喜欢
    • 2023-03-28
    • 1970-01-01
    • 2018-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-17
    相关资源
    最近更新 更多