首页 > 解决方案 > Python解析dict中的值

问题描述

我的代码如下

`res = [{'registryId': '660239311370', 'repositoryName': 'ecrpush', 'policyText': '{\n  "Version" : "2008-10-17",\n  "Statement" : [ {\n    "Sid" : "test-ecr",\n    "Effect" : "Allow",\n    "Principal" : "*",\n    "Action" : [ "ecr:DescribeImages", "ecr:ListImages", "ecr:GetRepositoryPolicy" ]\n  } ]\n}', 'ResponseMetadata': {'RequestId': 'cc920b7f-0de0-4d41-b40c-e1760f2fad20', 'HTTPStatusCode': 200, 'HTTPHeaders': {'x-amzn-requestid': 'cc920b7f-0de0-4d41-b40c-e1760f2fad20', 'date': 'Fri, 10 Apr 2020 22:34:15 GMT', 'content-type': 'application/x-amz-json-1.1', 'content-length': '319'}, 'RetryAttempts': 0}}, {'registryId': '660239311370', 'repositoryName': 'eks-c-ecrdo-lxuno80zkcoz', 'policyText': '{\n  "Version" : "2008-10-17",\n  "Statement" : [ {\n    "Sid" : "test-ecr",\n    "Effect" : "Allow",\n    "Principal" : "*",\n    "Action" : [ "ecr:DescribeImages", "ecr:GetRepositoryPolicy", "ecr:ListImages" ]\n  } ]\n}', 'ResponseMetadata': {'RequestId': '2519103c-8233-432d-85db-f59d1b89fe95', 'HTTPStatusCode': 200, 'HTTPHeaders': {'x-amzn-requestid': '2519103c-8233-432d-85db-f59d1b89fe95', 'date': 'Fri, 10 Apr 2020 22:34:15 GMT', 'content-type': 'application/x-amz-json-1.1', 'content-length': '336'}, 'RetryAttempts': 0}}, {'registryId': '660239311370', 'repositoryName': 'hello-codebuild', 'policyText': '{\n  "Version" : "2008-10-17",\n  "Statement" : [ {\n    "Sid" : "test",\n    "Effect" : "Allow",\n    "Principal" : {\n      "AWS" : "arn:aws:iam::660239311370:root"\n    },\n    "Action" : "ecr:StartLifecyclePolicyPreview"\n  } ]\n}', 'ResponseMetadata': {'RequestId': '400dd573-b9f3-4c18-a5da-e5cbedae7c73', 'HTTPStatusCode': 200, 'HTTPHeaders': {'x-amzn-requestid': '400dd573-b9f3-4c18-a5da-e5cbedae7c73', 'date': 'Fri, 10 Apr 2020 22:34:15 GMT', 'content-type': 'application/x-amz-json-1.1', 'content-length': '338'}, 'RetryAttempts': 0}}]

for r in res:
    policy_text = r['policyText']
    repo_name = r['repositoryName']

    print (policy_text)`

输出是:

{
  "Version" : "2008-10-17",
  "Statement" : [ {
    "Sid" : "test",
    "Effect" : "Allow",
    "Principal" : "*",
    "Action" : "ecr:StartLifecyclePolicyPreview"
  } ]
}

我想检查 Principal 是否为“*”。如何解析此输出?

提前致谢

标签: python-3.x

解决方案


假设每次迭代的结构都相同(即键和类型的名称相同):

policy_text.get('Statement', [{}])[0].get('Principal', None) == '*'

推荐阅读