使用JQ解析JSON文件并将其导出为CSV-BASH

时间:2018-03-13 09:53:25

标签: json bash jq

JSON文件:https://1drv.ms/u/s!AizscpxS0QM4hJl_VRQaWbm6D8T8_w

这是一节:

"RoleDetailList": [
        {
            "AssumeRolePolicyDocument": {
                "Version": "2012-10-17", 
                "Statement": [
                    {
                        "Action": "sts:AssumeRoleWithSAML", 
                        "Effect": "Allow", 
                        "Condition": {
                            "StringEquals": {
                                "SAML:aud": "https://signin.aws.amazon.com/saml"
                            }
                        }, 
                        "Principal": {
                            "Federated": "arn:aws:iam::279052847476:saml-provider/CompanyADFS"
                        }
                    }
                ]
            }, 
            "RoleId": "AROAJANL3L2IZ6UISEGAU", 
            "CreateDate": "2016-08-20T13:51:07Z", 
            "InstanceProfileList": [], 
            "RoleName": "ADFS-Administrators", 
            "Path": "/", 
            "AttachedManagedPolicies": [], 
            "RolePolicyList": [
                {
                    "PolicyName": "Administrator-Access", 
                    "PolicyDocument": {
                        "Version": "2012-10-17", 
                        "Statement": [
                            {
                                "Action": "*", 
                                "Resource": "*", 
                                "Effect": "Allow", 
                                "Sid": "Stmt1434192117145"
                            }
                        ]
                    }
                }
            ], 
            "Arn": "arn:aws:iam::279052847476:role/ADFS-Administrators"
        },

对于JSON文件中的所有这些部分,如何获得以下(仅此部分的示例)为CSV格式?

@Roman,您的解决方案有效,如何添加其他列,以从

获取策略名称
"AttachedManagedPolicies": [
                {
                    "PolicyName": "pol-amtest-ro", 
                    "PolicyArn": "arn:aws:iam::279052847476:policy/pol-amtest-ro"
                }
            ], 

1 个答案:

答案 0 :(得分:1)

jq 解决方案:

jq -r '.RoleDetailList 
       | map(select((.AssumeRolePolicyDocument.Statement | length > 0) 
                     and (.AssumeRolePolicyDocument.Statement[0].Principal.Federated) 
                     and (.RolePolicyList | length > 0))
         )[] 
       | [(.AssumeRolePolicyDocument.Statement[0] | .Action, .Principal.Federated),
           .RoleName, .RolePolicyList[0].PolicyName] | @csv' output.json

输出:

"sts:AssumeRoleWithSAML","arn:aws:iam::279052847476:saml-provider/companyADFS","ADFS-Administrators","Administrator-Access"