如何从JSON中提取特定部分并将其转换为CSV

时间:2018-03-12 15:14:22

标签: json bash jq aws-cli

output.json的一部分(文件有多个相同的部分 - 仅角色/策略名称不同)完整链接:https://1drv.ms/u/s!AizscpxS0QM4hJl_VRQaWbm6D8T8_w

{
  "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/LastPass"
        }
      }
    ]
  },
  "RoleId": "AROAI3SYPHW7ZSS4TSO6Y",
  "CreateDate": "2017-05-23T22:29:53Z",
  "InstanceProfileList": [],
  "RoleName": "AWSCorpAdmin",
  "Path": "/",
  "AttachedManagedPolicies": [
    {
      "PolicyName": "AdministratorAccess",
      "PolicyArn": "arn:aws:iam::aws:policy/AdministratorAccess"
    }
  ],
  "RolePolicyList": [],
  "Arn": "arn:aws:iam::279052847476:role/AWSCorpAdmin"
}

如何获取以下输出(将IAM角色映射到策略)并使用jq将其转换为csv文件?

jq -r '.AssumeRolePolicyDocument[]| .fields.RoleName |  @csv' output.json
jq: error (at output.json:11895): Cannot iterate over null (null)

期望的输出:

AWSCorpAdmin,AdministratorAccess 

我需要循环整个JSON文件并为每个角色获取策略(上面只是示例)

1 个答案:

答案 0 :(得分:3)

Data Frame 解决方案:

jq

示例输出:

jq -r '.RoleDetailList | map(select(.AttachedManagedPolicies | length > 0))[] 
       | .RoleName as $r | .AttachedManagedPolicies[] 
       | [$r, .PolicyName] | @csv' output.json