Jeremy Cowan
Jeremy Cowan

Reputation: 761

select value from an array using jq

I'm trying to write a query using jq that loops through the following json and returns the value of FileSystemId when the value of Name = "efs-docker" and breaks out of the script if no matching records are found. I thought I might be able to do it using a foreach loop, but the syntax is confusing. Is possible to do with with a reduce or select function instead?

{
   "FileSystems": [
     {
        "SizeInBytes": {
            "Value": 6144
        },
        "Name": "not-docker",
        "CreationToken": "console-db868fd6-ed6d-46f8-9e3e-4501293847f5",
        "CreationTime": 1440519280.0,
        "FileSystemId": "fs-0fdd32a6",
        "NumberOfMountTargets": 3,
        "LifeCycleState": "available",
        "OwnerId": "310444902345"
    },
    {
        "SizeInBytes": {
            "Timestamp": 1440514799.0,
            "Value": 307060736
        },
        "Name": "efs-docker",
        "CreationToken": "console-3b8b33de-dc45-4634-b6e1-882187ac3cd3",
        "CreationTime": 1440426036.0,
        "FileSystemId": "fs-d2c22d7b",
        "NumberOfMountTargets": 3,
        "LifeCycleState": "available",
        "OwnerId": "310444902345"
         }
    ]
}

Thanks, Jeremy

Upvotes: 0

Views: 284

Answers (2)

Hans Z.
Hans Z.

Reputation: 53888

Avoiding calling jq multiple times and thus avoiding the overhead of creating multiple processes:

jq -r '.FileSystems[] | select(.Name=="efs-docker") | .FileSystemId'

Upvotes: 3

Jeremy Cowan
Jeremy Cowan

Reputation: 761

I managed to do it using this:

jq '.FileSystems[]' | jq 'select(.Name=="efs-docker")' | jq -r '.FileSystemId'

It may not be efficient, but it worked.

Upvotes: 0

Related Questions