如何在python中访问深层JSON属性

时间:2012-01-06 04:27:19

标签: php python json

此PHP代码有效(json如下):

$usaData = json_decode(stripslashes(file_get_contents('usaJson.txt')),true);
foreach($usaData['USA']['States'] as $state){
    foreach($state['Cities'] as $city){
            $zipCode = $city['zipcode'];
        }
    }
}

我试图在python中做同样的事情,但它给了我<type 'exceptions.TypeError'>: string indices must be integers

usaData = json.loads(get_file('usaJson.txt'))
for state in usaData['USA']['States']:
    for city in state['Cities']:
        zipCode = city['zipcode']

我的数据结构如下:

{
  "USA":{
    "States":{
      "AL":{
        "Cities":[
          {
            "city":"auburn",
            "zipcode":"36830"
          },
          {
            "city":"birmingham",
            "zipcode":"35201"
          }
        ]
      },
      "AK":{
        "Cities":[
          {
            "city":"anchorage",
            "zipcode":"99501"
          },
          {
            "city":"fairbanks",
            "zipcode":"99701"
          }
        ]
      }
    }
  }
}

那么如何在python中访问zipcodes?

2 个答案:

答案 0 :(得分:1)

您的问题是迭代字典会为您提供密钥,而不是字典中的值。所以你需要的是:

for state_name in usaData['USA']['States']
  for city in usaData['USA']['States'][state_name]['Cities']
    print city['zipcode']

这非常难看

更好的版本是使用字典上的items函数,如下所示:

for state_name, state in usaData['USA']['States'].items():
  for city in state['Cities']
    print city['zipcode']

答案 1 :(得分:0)

for state in usaData.USA.States:

OR可能是,取决于结构:

for state in usaData.USA.States.all():

编辑:不漂亮,可以使用清理,但这应该有效:

for state in usaData['USA']['States'].keys():
    for cities in usaData['USA']['States'][state]['Cities']:
        print cities['zipcode']