1

I have the following json structure:

[
  {
    "IsDefault": false,
    "CidrBlock": "172.19.0.0/16",
    "DhcpOptionsId": "dopt-37fd70550",
    "State": "available",
    "CidrBlockAssociationSet": [
      {
        "CidrBlockState": {
          "State": "associated"
        },
        "CidrBlock": "172.19.0.0/16",
        "AssociationId": "vpc-cidr-assoc-f3c1559a"
      }
    ],
    "Tags": [
      {
        "Key": "Name",
        "Value": "product-Production"
      }
    ],
    "InstanceTenancy": "default",
    "VpcId": "vpc-1f0e197d"
  },
  {
    "IsDefault": false,
    "CidrBlock": "10.0.0.0/16",
    "DhcpOptionsId": "dopt-0a550861",
    "State": "available",
    "CidrBlockAssociationSet": [
      {
        "CidrBlockState": {
          "State": "associated"
        },
        "CidrBlock": "10.0.0.0/16",
        "AssociationId": "vpc-cidr-assoc-8955dae0"
      }
    ],
    "Tags": [
      {
        "Key": "Name",
        "Value": "Marketing VPC"
      }
    ],
    "InstanceTenancy": "default",
    "VpcId": "vpc-36b5585d"
  },
  .
  .
  .
]

I'm trying to print all VpcId's using jq but I can't find the right way to do it.

Here's what I've tried:

command | jq -r '.VpcId[]'
command | jq -r '.VpcId'
command | jq -r '.[] | .VpcId'

What am I doing wrong?

peak
  • 105,803
  • 17
  • 152
  • 177
Itai Ganot
  • 5,873
  • 18
  • 56
  • 99

2 Answers2

2

It looks like the command you are using is aws ec2 describe-vpcs.

This command actually returns the following structure:

{
    "Vpcs": [
        {
            "VpcId": "vpc-xxxxxxxx", 
        }
    ]
}

So you want to reach into the Vpcs key before you iterate over the array, Like this:

aws ec2 describe-vpcs | jq -r '.Vpcs | .[] | .VpcId'
Mike Patrick
  • 10,699
  • 1
  • 32
  • 54
0

An alternative to consider would be to use .., e.g.

.. | .VpcId? // empty

will print the values of all "VpcId" keys, except for null and false values.

Incidentally, .Vpcs | .[] | .VpcId can be abbreviated to .Vpcs[].VpcId

peak
  • 105,803
  • 17
  • 152
  • 177