Ad

Iterating Through Json Lists

- 1 answer

I am learning python, mainly for use with AWS, and find myself looping through json quite alot, but I often encounter the "list indices must be integers or slices, not str" error.

for example in the 'response' json data below, I want to get to the ['Names'] and ['ImagesId'] from each returned object, but because it's a list I get the error.

for i in response:
print(response['Images'][i]['Name'])
print(response['Images'][i]['ImageId'])

TypeError: list indices must be integers or slices, not str

I've been using the length of the returned data to create a range object, which seems to work OK, but I've read this isn't very pythonic and thought it was time to find out the right way to do this.. Apologies in advance if I have missed something basic or misunderstood what I have read..

response_count = range(len(response['Images']))

for i in response_count:
    print(response['Images'][i]['Name'])
    print(response['Images'][i]['ImageId'])

aws-elasticbeanstalk-amzn-2018.01.05.x86_64-WindowsServer2012R2-hvm-201801102240
ami-c3554ea7
aws-elasticbeanstalk-amzn-2018.01.12.x86_64-WindowsServer2012R2-hvm-201802141022
ami-dd15f0ba

Example returned JSON

{
  "Images": [
{
  "Architecture": "x86_64",
  "CreationDate": "2018-01-10T23:33:52.000Z",
  "ImageId": "ami-c3554ea7",
  "ImageLocation": "amazon/aws-elasticbeanstalk-amzn-2018.01.05.x86_64-WindowsServer2012R2-hvm-201801102240",
  "ImageType": "machine",
  "Public": true,
  "OwnerId": "102837901569",
  "Platform": "windows",
  "State": "available",
  "EnaSupport": true,
  "Hypervisor": "xen",
  "ImageOwnerAlias": "amazon",
  "Name": "aws-elasticbeanstalk-amzn-2018.01.05.x86_64-WindowsServer2012R2-hvm-201801102240",
  "RootDeviceName": "/dev/sda1",
  "RootDeviceType": "ebs",
  "SriovNetSupport": "simple",
  "VirtualizationType": "hvm"
},
{
  "Architecture": "x86_64",
  "CreationDate": "2018-02-14T11:10:40.000Z",
  "ImageId": "ami-dd15f0ba",
  "ImageLocation": "amazon/aws-elasticbeanstalk-amzn-2018.01.12.x86_64-WindowsServer2012R2-hvm-201802141022",
  "ImageType": "machine",
  "Public": true,
  "OwnerId": "102837901569",
  "Platform": "windows",
  "State": "available",
  "EnaSupport": true,
  "Hypervisor": "xen",
  "ImageOwnerAlias": "amazon",
  "Name": "aws-elasticbeanstalk-amzn-2018.01.12.x86_64-WindowsServer2012R2-hvm-201802141022",
  "RootDeviceName": "/dev/sda1",
  "RootDeviceType": "ebs",
  "SriovNetSupport": "simple",
  "VirtualizationType": "hvm"
}
  ]
}
Ad

Answer

This should help.

for i in response['Images']:
    print(i['Name'])
    print(i['ImageId'])

Output:

aws-elasticbeanstalk-amzn-2018.01.05.x86_64-WindowsServer2012R2-hvm-201801102240
ami-c3554ea7
aws-elasticbeanstalk-amzn-2018.01.12.x86_64-WindowsServer2012R2-hvm-201802141022
ami-dd15f0ba
Ad
source: stackoverflow.com
Ad