Issue
I have below output.
<class 'str'>
[{
"AssociatePublicIpAddress": true,
"DeleteOnTermination": true,
"Description": "Primary network interface",
"DeviceIndex": 0,
"Groups": ["sg-0b11476a38d83dba3", "sg-80e269f9"],
"Ipv6AddressCount": 0,
"Ipv6Addresses": [],
"NetworkInterfaceId": "eni-45fe4079",
"PrivateIpAddress": "172.31.38.42",
"PrivateIpAddresses": [{
"Primary": true,
"PrivateIpAddress": "172.31.38.42"
}],
"SecondaryPrivateIpAddressCount": 0,
"SubnetId": "subnet-3d03d94b",
"InterfaceType": "interface",
"Ipv4Prefixes": [],
"Ipv6Prefixes": []
}]
And I want to print in two lines
"Groups":
["sg-0b11476a38d83dba3", "sg-80e269f9"]
How can i do that in python?
I am trying to understand how to parse AWS API outputs in boto3 to build some automation. Is there any specific resource I can study that can help me master parsing AWS / Boto3 API in python?
Solution
txt = """
[{ "AssociatePublicIpAddress": true, "DeleteOnTermination": true, "Description": "Primary network interface",
"DeviceIndex": 0, "Groups": ["sg-0b11476a38d83dba3", "sg-80e269f9"], "Ipv6AddressCount": 0, "Ipv6Addresses": [],
"NetworkInterfaceId": "eni-45fe4079", "PrivateIpAddress": "172.31.38.42", "PrivateIpAddresses":
[{ "Primary": true, "PrivateIpAddress": "172.31.38.42" }], "SecondaryPrivateIpAddressCount": 0, "SubnetId":
"subnet-3d03d94b", "InterfaceType": "interface", "Ipv4Prefixes": [], "Ipv6Prefixes": [] }]
"""
d = json.loads(txt)
>>> d
[{'AssociatePublicIpAddress': True,
'DeleteOnTermination': True,
'Description': 'Primary network interface',
'DeviceIndex': 0,
'Groups': ['sg-0b11476a38d83dba3', 'sg-80e269f9'],
'Ipv6AddressCount': 0,
'Ipv6Addresses': [],
'NetworkInterfaceId': 'eni-45fe4079',
'PrivateIpAddress': '172.31.38.42',
'PrivateIpAddresses': [{'Primary': True,
'PrivateIpAddress': '172.31.38.42'}],
'SecondaryPrivateIpAddressCount': 0,
'SubnetId': 'subnet-3d03d94b',
'InterfaceType': 'interface',
'Ipv4Prefixes': [],
'Ipv6Prefixes': []}]
and
>>> d[0].get('Groups')
['sg-0b11476a38d83dba3', 'sg-80e269f9']
# or (for all elements in the list)
>>> [di.get('Groups') for di in d]
[['sg-0b11476a38d83dba3', 'sg-80e269f9']]
BTW, you'll definitely benefit by using boto3
instead of AWS cli for scripts etc. For quick things on the command line, AWS cli is awesome. When you start to want to do some real automation around AWS services, I find boto3
+ Python
hard to beat.
Answered By - Pierre D
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.