Parvez Kazi
Parvez Kazi

Reputation: 775

Concatenate json array objects with jq

I have below json file :

{
"EventId": "60a0490c",
"Resources": [
    {
        "ResourceType": "AWS::STS::AssumedRole", 
        "ResourceName": "AutoScaling"
    }, 
    {
        "ResourceType": "AWS::IAM::Role", 
        "ResourceName": "arn:aws:iam:autoscaling.amazonaws.com/AWSServiceRoleForAutoScaling"
    }
    ]
}

I want to concatenate the key-value pairs from Resources element, and output on single line as:

60a0490c,AutoScaling=AWS::STS::AssumedRole#AWS::IAM::Role=arn:aws:iam:autoscaling.amazonaws.com/AWSServiceRoleForAutoScaling

I tried it as :

cat file.json | jq '.EventId + "," + (.Resources[] | join("="))' -r

It gives me output as :

60a0490c,AutoScaling=AWS::STS::AssumedRole
60a0490c,AutoScaling=AWS::IAM::Role=arn:aws:iam:autoscaling.amazonaws.com/AWSServiceRoleForAutoScaling

It creates new entry for each key-value pair, I want it to be on single line with different delimeter (#)

Thanks in advance.

Upvotes: 1

Views: 522

Answers (1)

oliv
oliv

Reputation: 13249

You can try this:

jq ' .EventId + "," + ([(.Resources[] | join("="))] | join("#"))' -r file
60a0490c,AWS::STS::AssumedRole=AutoScaling#AWS::IAM::Role=arn:aws:iam:autoscaling.amazonaws.com/AWSServiceRoleForAutoScaling

To use the second join(), just enclose the result in an array [...].

Note that the first key/value is not swapped as shown in your example (i.e. Autoscaling is the value and not the key).

Upvotes: 6

Related Questions