Skip to content

Instantly share code, notes, and snippets.

@imksoo
Last active February 15, 2018 03:12
Show Gist options
  • Save imksoo/4fd6055226b217a27f6c0d358481e066 to your computer and use it in GitHub Desktop.
Save imksoo/4fd6055226b217a27f6c0d358481e066 to your computer and use it in GitHub Desktop.

Pythonのformatは便利

import json

json_text = '''{
    "version": "0",
    "id": "6a7e8feb-b491-4cf7-a9f1-bf3703467718",
    "detail-type": "EC2 Instance State-change Notification",
    "source": "aws.ec2",
    "account": "111122223333",
    "time": "2015-12-22T18:43:48Z",
    "region": "us-east-1",
    "resources": [
        "arn:aws:autoscaling:us-east-1:123456789012:autoScalingGroup:eb56d16b-bbf0-401d-b893-d5978ed4a025:autoScalingGroupName/ASGTerminate",
        "arn:aws:ec2:us-east-1:123456789012:instance/i-b188560f"
    ],
    "detail": {
        "instance-id": "i-12345678",
        "state": "terminated"
    }
}'''
d = json.loads(json_text)
'{0[resources]}'.format(d)
"['arn:aws:autoscaling:us-east-1:123456789012:autoScalingGroup:eb56d16b-bbf0-401d-b893-d5978ed4a025:autoScalingGroupName
/ASGTerminate', 'arn:aws:ec2:us-east-1:123456789012:instance/i-b188560f']"
>>> '{0[resources][1]}'.format(d)
'arn:aws:ec2:us-east-1:123456789012:instance/i-b188560f'

>>> '{0[detail]}'.format(d)
"{'instance-id': 'i-12345678', 'state': 'terminated'}"

>>> '{0[detail][instance-id]}'.format(d)
'i-12345678'

>>> '{detail[instance-id]}'.format(**d)
'i-12345678'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment