pedro
pedro

Reputation: 165

How to filter properly with JQ

I have this:

{
  "LaunchTemplateVersions": [
    {
      "LaunchTemplateId": "lt-xxxxxx",
      "LaunchTemplateName": "dev-xxxxxx",
      "VersionNumber": 1,
      "VersionDescription": "dev-xxxxx",
      "CreateTime": "2021-04-28T06:12:15+00:00",
      "CreatedBy": "arn:aws:sts::xxxxx",
      "DefaultVersion": true,
      "LaunchTemplateData": {
        "BlockDeviceMappings": [
          {
            "DeviceName": "/dev/xvda",
            "Ebs": {
              "Encrypted": true,
              "DeleteOnTermination": true,
              "KmsKeyId": "arn:aws:kms:xxxx",
              "SnapshotId": "snap-xxxx",
              "VolumeSize": 800,
              "VolumeType": "gp2"
            }
          }

and I need to get values for:

doing: jq -r '.LaunchTemplateVersions[].LaunchTemplateData[].DeviceName'

does return: Cannot index array with string "DeviceName"

I guess question is how can I get this right but also, how can I understan JQ filtering on my own, like knowing rules, etc..

TY

Upvotes: 0

Views: 565

Answers (1)

peak
peak

Reputation: 116987

Assuming the illustrative input has been corrected in the obvious way so that it is valid JSON, the invocation:

jq -r '
  .LaunchTemplateVersions[].LaunchTemplateData.BlockDeviceMappings[]
  | (.DeviceName, .Ebs.KmsKeyId,.Ebs.VolumeSize)' input.json

would yield:

/dev/xvda
arn:aws:kms:xxxx
800

Learning Resources

Since you asked about learning resources, let me mention that in addition to the resources mentioned on the jq wiki, you might like to browse through the guide I wrote: A Stream-Oriented Introduction to jq.

Upvotes: 1

Related Questions