代码之家  ›  专栏  ›  技术社区  ›  arod

在任何级别使用jq搜索字符串

  •  0
  • arod  · 技术社区  · 6 年前

    我想用 jq 提取钥匙的任何外观 Action 在JSON文件中。 行动 多次出现在JSON中不同路径(或同一路径键结构具有不同值)中。

    用例是提取所有提供 * 权限。

    "*" 作为一种元素,比如

    "Action":["not this", "*", "not that"]
    

    "Action" 达到一定程度以上。

    例如,这个JSON:

        {
            "AssumeRolePolicyDocument": {
                "Version": "2012-10-17",
                "Statement": [
                    {
                        "Action": "*",
                        "Effect": "Allow",
                        "Principal": {
                            "Service": "ec2.amazonaws.com"
                        }
                    }
                ]
            },
            ...
    

    它会被提取出来

        {
            "AssumeRolePolicyDocument": {
                "Version": "2012-10-17",
                "Statement": [
                    {
                        "Action": "*",
                        "Effect": "Allow",
                        "Principal": {
                            "Service": "ec2.amazonaws.com"
                        }
                    }
                ]
            },
            ...
        }
    

    这是可以实现的吗 jq公司 ,怎么办?

    2 回复  |  直到 6 年前
        1
  •  1
  •   peak    6 年前

    获取满足条件的路径和对象

    [本节按最初的措辞处理问题,即当问题具体要求到感兴趣的对象的路径时。]

    paths(objects and has("Action") 
          and (.Action == "*" or (.Action|index("*")))) as $path
    | [ $path, getpath($path)]
    

    根据选择标准折叠输入

    . as $in
    | reduce paths(objects and has("Action")
                   and (.Action == "*" or (.Action|index("*")))) as $path
        ({}; setpath($path; $in | getpath($path)))
    

    {
      "AssumeRolePolicyDocument": {
        "Statement": [
          {
            "Action": "*",
            "Effect": "Allow",
            "Principal": {
              "Service": "ec2.amazonaws.com"
            }
          }
        ]
      }
    }