Reputation: 543
I have a JSON script in which I need to fetch out series of values using loops in Python. Sample Json snippet is shown below,
{
'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'
}]
}]
}
In the above json, I need to fetch 'DestinationPrefixListId'. As I am new to Python loop concept using boto3 (SDK for aws and python) library, not able to fetch the list. Any suggestion?
Upvotes: 0
Views: 103
Reputation: 543
Thanks for the comments and help. I have formed a for loop and got the required output. Please find the below code,
r = data['RouteTables'][0]['Routes']
for x in r:
a = x
if 'DestinationPrefixListId' in r[x]:
b = a.get('DestinationPrefixListId')
"data" denotes the above Json posted. Using the above code, I am able to get the values that are required. Thank you all. Have a good day!!
Upvotes: 0
Reputation: 832
I am not sure if I understand your task correct:
[y.get("DestinationPrefixListId") for x in data["RouteTables"] for y in x["Routes"] if y.get("DestinationPrefixListId")]
Will return:
['pl-234234', 'pl-2342344']
Upvotes: 1