使用Python从Json脚本循环并获取值

2024-09-30 18:20:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个JSON脚本,其中需要使用Python中的循环提取一系列值。示例Json片段如下所示

{
    'ResponseMetadata': {
        'RetryAttempts': 0,
        'HTTPStatusCode': 200,
        'RequestId': 'aaaaaaaaaaaa',
        'HTTPHeaders': {
            'date': 'Tue, 19 Nov 2019 12:40:10 GMT',
            'vary': 'accept-encoding',
            'content-length': '2236',
            'content-type': 'text/xml;charset=UTF-8',
            'server': 'AmazonEC2'
        }
    },
    u 'RouteTables': [{
        u 'Associations': [{
            u 'SubnetId': 'subnet-aaaaaa',
            u 'RouteTableAssociationId': 'rtvvvvvvv-24234234234234',
            u 'Main': False,
            u 'RouteTableId': 'rtb-32423423'
        }, {
            u 'RouteTableAssociationId': 'rtbassoc-ebec234324',
            u 'Main': True,
            u 'RouteTableId': 'rtb-324234234'
        }],
        u 'RouteTableId': 'rtb-234234',
        u 'VpcId': 'vpc-2342342',
        u 'PropagatingVgws': [],
        u 'Tags': [],
        u 'Routes': [{
            u 'GatewayId': 'local',
            u 'DestinationCidrBlock': '435.43.0.0/16',
            u 'State': 'active',
            u 'Origin': 'CreateRouteTable'
        }, {
            u 'GatewayId': 'igw-a234234',
            u 'DestinationCidrBlock': '0.0.0.0/0',
            u 'State': 'active',
            u 'Origin': 'CreateRoute'
        }, {
            u 'GatewayId': 'vpce-234234',
            u 'Origin': 'CreateRoute',
            u 'State': 'active',
            u 'DestinationPrefixListId': 'pl-234234'
        }, {
            u 'GatewayId': 'vpce-sadasdsaddds4',
            u 'Origin': 'CreateRoute',
            u 'State': 'active',
            u 'DestinationPrefixListId': 'pl-2342344'
        }]
    }]
}

在上面的json中,我需要获取'DestinationPrefixListId'。由于我不熟悉使用boto3(aws和Python的SDK)库的Python循环概念,所以无法获取列表。有什么建议吗?你知道吗


Tags: jsonmainorigincontentactiveplstatertb
2条回答

我不确定我是否正确理解您的任务:

[y.get("DestinationPrefixListId") for x in data["RouteTables"] for y in x["Routes"] if y.get("DestinationPrefixListId")]

将返回:

['pl-234234', 'pl-2342344']

谢谢你的评论和帮助。我已经形成了for循环并得到了所需的输出。请查找以下代码

r = data['RouteTables'][0]['Routes']
for x in r:
   a = x 
   if 'DestinationPrefixListId' in r[x]:
      b =  a.get('DestinationPrefixListId')

“data”表示上面发布的Json。使用上面的代码,我能够得到所需的值。谢谢大家。祝您今天过得愉快!!你知道吗

相关问题 更多 >