python-3.x - 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 是否为“*”。如何解析此输出?
提前致谢
解决方案
假设每次迭代的结构都相同(即键和类型的名称相同):
policy_text.get('Statement', [{}])[0].get('Principal', None) == '*'
推荐阅读
- javascript - 从 Vue.js 开始,什么都没有显示
- apache-nifi - Nifi PutDatabaseRecord 使用 where 条件更新表
- python - 我有一个 Excel 文件。如何使用 Jupyther Notebook 和 Python 将其转换为结构适合 DWH 的表
- razor - 在 Blazor WASM 中更改授权布局
- scala - 如何使用 Scala 更新不可变数组中的特定元素
- ffmpeg - 元数据 ffmpeg
- spring - 在部署在 aws 上的单个 Spring 服务实例上运行 chron 作业
- html - 如何在 html if 块中添加不同的颜色背景?
- python - 使用 Apply 根据现有列创建新的数据框列
- pine-script - Pine Script - 2 条件多头入场(定制策略 + MACD 交叉)