Print all matching JSON dictionaries in Python
<p>I am currently using the AWS Boto3 to try to get a list of all of my current running EC2 instances. I am at the point where I am able to use describe_instances to list all of my instances, but I am trying to figure out how to pull out all of the instance ID's so I can print them AND use them for another part of the script. Ultimately, I have one script that spins up all of the instance, next I want one that tears them all down. </p>

<p>JSON Tree bellow.</p>

<p>To select a specifc one, I have to do this, </p>

<pre><code>instance_id = response['Reservations'][0]['Instances'][0]['InstanceId']
</code></pre>

<p>But I want to be able to select all instances, regardless of how many instances I have, so trying to do [0][1] etc isn't feasable, so not sure how I would go about saying I want every InstanceId that is in the command.</p>

<pre><code>{
    u'Reservations': [
        {
            u'Groups': [

            ],
            u'Instances': [
                {
                    u'AmiLaunchIndex': 0,
                    u'Architecture': 'i386',
                    u'EbsOptimized': False,
                    u'Hypervisor': 'xen',
                    u'InstanceId': 'i-6fb4ad61',
                }
            ],
            u'OwnerId': '',
            u'ReservationId': ''
        },
        {
            u'Groups': [

            ],
            u'Instances': [
                {
                    u'AmiLaunchIndex': 0,
                    u'Architecture': 'i386',
                    u'EbsOptimized': False,
                    u'Hypervisor': 'xen',
                    u'InstanceId': 'i-afe3faa1',
                }
            ],
            u'OwnerId': '',
            u'ReservationId': ''
        }
    ],
    'ResponseMetadata': {
        'HTTPHeaders': {
            'content-type': 'text/xml;charset=UTF-8',
            'date': 'Thu, 25Aug201623: 44: 09GMT',
            'server': 'AmazonEC2',
            'transfer-encoding': 'chunked',
            'vary': 'Accept-Encoding'
        },
        'HTTPStatusCode': 200,
        'RequestId': ''
    }
}
</code></pre>

<p>Here is the command I am using to get the instance ID.</p>

<pre><code>launch_instance = ec2.create_instances(ImageId="xxxxxx", MinCount=1, MaxCount=1,SecurityGroupIds=["sg-xxxxxxx"],InstanceType='m3.medium', SubnetId='subnet-xxxxx')


response = ec2client.describe_instances(
    InstanceIds=[
        launch_instance[0].id],
)

instance_id = response['Reservations'][0]['Instances'][0]['InstanceId']

print instance_id
</code></pre>

<p>output is i-6fb4ad61</p>

<p>Try this</p>

<pre><code>instance_ids = []
for reservations in response['Reservations']:
    for instance in reservations['Instances']:
        instance_ids.append(instance['InstanceId'])
</code></pre>

python json amazon-web-services amazon-ec2 boto3