Home > database >  How to extract an attribute's value from JSON object when another attribute's value from s
How to extract an attribute's value from JSON object when another attribute's value from s

Time:08-18

In a bash shell script, I want to extract Arn, DefaultVersionId from following JSON where Arn string contains word akshay:

[
    {
            "PolicyName": "my-buckets-all",
            "PolicyId": "ABCDEF",
            "Arn": "arn:aws:iam::12345:policy/my-buckets-all",
            "Path": "/",
            "DefaultVersionId": "v1",
            "AttachmentCount": 0,
            "PermissionsBoundaryUsageCount": 0,
            "IsAttachable": true,
            "CreateDate": "2022-05-14T01:17:13 00:00",
            "UpdateDate": "2022-05-14T01:17:13 00:00"
        },
        {
            "PolicyName": "akshay-buckets-all",
            "PolicyId": "GHIJK",
            "Arn": "arn:aws:iam::12345:policy/akshay-buckets-all",
            "Path": "/",
            "DefaultVersionId": "v4",
            "AttachmentCount": 1,
            "PermissionsBoundaryUsageCount": 0,
            "IsAttachable": true,
            "CreateDate": "2022-05-20T21:20:10 00:00",
            "UpdateDate": "2022-07-28T19:15:09 00:00"
        }
]

I am fiddling with jq to get this done. When tried with following, I just get the Arn and not DefaultVersionId:

.[] | .Arn, .DefaultVersionId | select(contains("akshay"))

How to go about it?

jqplay fiddle here: https://jqplay.org/s/gp1DYAG-rgU

CodePudding user response:

You need to filter the required objects first (based on your condition) and then extract the fields needed, i.e.

map( select( .Arn | contains( "akshay" ) )? )[] | .Arn, .DefaultVersionId

gets you the values on a multi-line output. To get the values on the same line separated by a single whitespace use "\(.Arn) \(.DefaultVersionId)" after the pipe symbol.

Note that contains looks for an exact match of the search string and does not satisfy case insensitivity. To do so use test("akshay"; "i") instead.

jqplay link - https://jqplay.org/s/JzzfzqYWXYN

  • Related