【问题标题】:Split "/" with complex conditions in JQ在 JQ 中使用复杂条件拆分“/”
【发布时间】:2021-11-18 14:41:34
【问题描述】:

我有 json:

    "spec": {
        "background": true,
        "failurePolicy": "Fail",
        "rules": [
            {
                "exclude": {
                    "resources": {}
                },
                "generate": {
                    "clone": {}
                },
                "match": {
                    "resources": {
                        "kinds": [
                            "networking.k8s.io/v1/NetworkPolicy"
                        ]
                    }
                },
                "mutate": {},
                "name": "validate-nodeport",
                "validate": {
                    "message": "Services of type NodePort are not allowed.",
                    "pattern": {
                        "spec": {
                            "type": "!NodePort"
                        }
                    }
                }
            }
        ],
        "validationFailureAction": "audit"
    },
    "status": {
        "ready": true
    }
}

我需要解析这个字符串"networking.k8s.io/v1/NetworkPolicy",但它可能看起来像KindVersion/KindVersion/Group/Kind。我的 jq 命令仅适用于 Kind 案例:.spec.rules[0].match.resources.kinds[] as $kind

我需要更通用的命令来将字符串拆分为“/”,但在某些情况下可能有一个“/”,在某些情况下可能有两个。我需要正确解析它并编写带有条件的命令

【问题讨论】:

    标签: jq


    【解决方案1】:

    您可以使用/ 运算符和分隔符(在您的情况下为"/")将字符串拆分为数组:

    .spec.rules[0].match.resources.kinds / "/"
    
    [
      "networking.k8s.io",
      "v1",
      "NetworkPolicy"
    ]
    

    然后,根据元素的存在重新排列:

    ... | [select(.[1])[0] // null, select(.[2])[1] // null, last]
    

    最后,一次将数组元素分配给多个变量:

    ... as [$version,$group,$kind]
    

    综合:

    (.spec.rules[0].match.resources.kinds / "/")
    | [select(.[1])[0] // null, select(.[2])[1] // null, last]
      as [$version,$group,$kind]
    | {$version,$group,$kind}
    

    Demo

    【讨论】:

    • 我需要像 $ver, $gr, $kind 一样解析它,例如当版本或组没有被定义时
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-05
    • 2010-12-28
    • 1970-01-01
    • 2022-11-24
    • 2017-06-30
    相关资源
    最近更新 更多