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

如何在bash中使用jq过滤器过滤关键字和值

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

    运行以下命令后

    aws ec2 describe-tags --filter "Name=resource-id,Values=i-8dh7435490fjksfd"

    {
        "Tags": [
            {
                "ResourceType": "instance", 
                "ResourceId": "i-8dh7435490fjksfd", 
                "Value": "production", 
                "Key": "Environment"
            }, 
            {
                "ResourceType": "instance", 
                "ResourceId": "i-8dh7435490fjksfd", 
                "Value": "webserver", 
                "Key": "Application"
            }
        ]
    }
    

    如何使用jq过滤器获得以下输出

    应用程序:Web服务器

    3 回复  |  直到 6 年前
        1
  •  3
  •   helloV    6 年前

    不使用的解决方案 jq

    aws ec2 describe-tags   --filter "Name=resource-id,Values=i-8dh7435490fjksfd" --query 'Tags[?Key==`Application`].Value[]' --output text
    
        2
  •  3
  •   peak    6 年前
    .Tags[]
    | select(.Key == "Application")
    | "\(.Key) : \(.Value)"
    
        3
  •  -1
  •   mohit    6 年前

    你可以通过使用jq以这种方式获得它。在键周围加括号意味着它将作为表达式进行计算。

    cat example.json | jq '.[] | {(.[].Key): (.[].Value)}'
    

    输出:

    {
      "Environment": "production"
    }
    {
      "Environment": "webserver"
    }
    {
      "Application": "production"
    }
    {
      "Application": "webserver"
    }
    

    https://stedolan.github.io/jq/manual/