使用JQ和从预过滤的JSON中提取键值对数组

icnyk63a  于 2023-02-01  发布在  其他
关注(0)|答案(2)|浏览(136)

我想从下面的JSON中提取一个键值对数组,这个数组是由下面的AWS CLI脚本生成的。这个数组应该包含负载平衡器的名称。

aws elbv2 describe-load-balancers | jq '.LoadBalancers[] | select(.LoadBalancerName | startswith("MY_LOAD_BALANCER_NAME"))'

我试着在这个脚本的末尾添加一个JQ过滤器,如下所示,但是没有效果:

aws elbv2 describe-load-balancers | jq '.LoadBalancers[] | select(.LoadBalancerName | startswith("MY_LOAD_BALANCER_NAME"))' | jq -r .LoadBalancers[].LoadBalancerName

下面是我的JSON输出的简化版本:

{
    "LoadBalancers": [
        {
            "LoadBalancerArn": "arn:aws:elasticloadbalancing...",
            "CreatedTime": "2023-01-26T22:26:42.313000+00:00",
            "LoadBalancerName": "elb_name_123"
        },
        {
            "LoadBalancerArn": "arn:aws:elasticloadbalancing...",
            "CreatedTime": "2023-01-26T22:26:42.313000+00:00",
            "LoadBalancerName": "elb_name_456"
        },
        {
            "LoadBalancerArn": "arn:aws:elasticloadbalancing...",
            "CreatedTime": "2023-01-26T22:26:42.313000+00:00",
            "LoadBalancerName": "elb_name_789"
        }
    ]
}
fxnxkyjh

fxnxkyjh1#

我不知道这是不是你想要的输出格式.这个怎么样?

cat output.json | jq '[.LoadBalancers[] | select(.LoadBalancerName | startswith("elb_name")) | { LoadBalancerName: .LoadBalancerName } ]'
[
  {
    "LoadBalancerName": "elb_name_123"
  },
  {
    "LoadBalancerName": "elb_name_456"
  },
  {
    "LoadBalancerName": "elb_name_789"
  }
]
$ cat output.json 
{
  "LoadBalancers": [
    {
      "LoadBalancerArn": "arn:aws:elasticloadbalancing...",
      "CreatedTime": "2023-01-26T22:26:42.313000+00:00",
      "LoadBalancerName": "elb_name_123"
    },
    {
      "LoadBalancerArn": "arn:aws:elasticloadbalancing...",
      "CreatedTime": "2023-01-26T22:26:42.313000+00:00",
      "LoadBalancerName": "elb_name_456"
    },
    {
      "LoadBalancerArn": "arn:aws:elasticloadbalancing...",
      "CreatedTime": "2023-01-26T22:26:42.313000+00:00",
      "LoadBalancerName": "elb_name_789"
    }
  ]
}
h79rfbju

h79rfbju2#

你不需要使用额外的jq来过滤AWS cli已经支持jmespath了。
可以使用starts_with筛选负载平衡器

aws elbv2 describe-load-balancers --query 'LoadBalancers[?starts_with(LoadBalancerName, `elb_name`)].LoadBalancerName'

相关问题