Home > Software design >  Extract an array of key-value pairs using JQ and from pre-filtered JSON
Extract an array of key-value pairs using JQ and from pre-filtered JSON

Time:01-31

I want to extract an array of key-value pairs from the below JSON, that is generated by the following AWS CLI script. The array should contain the load balancer names.

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

I tried adding a JQ filter to the end of this script, as follows, but it did not work:

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

Here's a shorten version of my JSON output:

{
    "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"
        }
    ]
}

CodePudding user response:

I don't know if this is the output format you want. How about this?

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"
    }
  ]
}

CodePudding user response:

You don't need to use an extra jq for filtering AWS cli supports jmespath already.

You can filter loadbalancers with starts_with

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