用jq连接json数组对象

时间:2018-09-18 10:14:49

标签: json bash jq aws-cli

我有下面的json文件:

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

我想连接Resources元素中的键/值对,并在单行上输出为:

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

我尝试过:

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

它给我的输出为:

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

它为每个键值对创建一个新条目,我希望它位于具有不同分隔符(#)的单行中

谢谢。

1 个答案:

答案 0 :(得分:6)

您可以尝试以下方法:

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

要使用第二个join(),只需将结果封装在数组[...]中。

请注意,第一个键/值不会像您的示例所示那样交换(即Autoscaling是值而不是键)。