apdcm
apdcm

Reputation: 99

How can I filter a block of data out of a big JSON output by value using JQ?

When I run this command to get the status on an image import:

aws ec2 describe-import-image-tasks

I'm presented with the following example JSON, but these are all the images I've imported:

{
"ImportImageTasks": [
    {
        "Architecture": "x86_64",
        "ImageId": "ami-99999999",
        "ImportTaskId": "import-ami-00000000",
        "LicenseType": "BYOL",
        "Platform": "Linux",
        "Status": "completed"
    },
    {
        "Architecture": "x86_64",
        "ImageId": "ami-88888888",
        "ImportTaskId": "import-ami-11111111",
        "LicenseType": "BYOL",
        "Platform": "Linux",
        "Status": "completed"
    },
    {
        "Architecture": "x86_64",
        "ImageId": "ami-77777777",
        "ImportTaskId": "import-ami-22222222",
        "LicenseType": "BYOL",
        "Platform": "Linux",
        "Status": "completed"
        }
    ]
}

I would only like the block that matches the ImageId I specify. Like so:

{
    "Architecture": "x86_64",
    "ImageId": "ami-77777777",
    "ImportTaskId": "import-ami-22222222",
    "LicenseType": "BYOL",
    "Platform": "Linux",
    "Status": "completed"
}

How can I do this with JQ?

Upvotes: 0

Views: 63

Answers (1)

Charles Duffy
Charles Duffy

Reputation: 295403

If you want to extract only the one block:

jq --arg id ami-77777777 '.ImportImageTasks[] | select(.ImageId==$id)'

If you want to filter the blocks, and return a document with the same form but all other ImageImportTask blocks removed:

jq --arg id ami-77777777 '.ImportImageTasks |= [.[] | select(.ImageId==$id)]'

Upvotes: 3

Related Questions