简体   繁体   中英

How to access deep JSON attributes in python

This PHP code works (json below):

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

I tried to do the same in python but it gave me <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']

My data structure is like this:

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

So how do I access the zipcodes in python?

Your problem is that iterating over a dictionary gives you the key, not the value in the dictionary. So what you need is this:

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

Which is remarkably ugly

A nicer version is to use an the items function on the dictionary, which looks like this:

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

OR might be, depending on structure:

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

EDIT: Not pretty, could use clean-up, but this should work:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM