迭代json列表

时间:2018-03-03 09:26:17

标签: python python-3.x aws-sdk

我正在学习python,主要用于AWS,并发现自己在json中循环很多,但我经常遇到“列表索引必须是整数或切片,而不是str”错误。

例如在下面的'响应'json数据中,我想从每个返回的对象到达['Names']和['ImagesId'],但因为它是一个列表,我得到了错误。

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

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

我一直在使用返回数据的长度来创建一个范围对象,这似乎工作正常,但我读到这不是非常pythonic,并认为是时候找出正确的方法做如果我错过了一些基本的或误解了我所读过的内容,请提前道歉..

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

示例返回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"
}
  ]
}

0 个答案:

没有答案