简体   繁体   中英

TypeError : Trouble accessing JSON metadata with Python

So I'm trying to access the following JSON data with python and when i give the statement :

print school['students'] 

The underlying data gets printed but what I really want to be able to do is print the 'id' value.

   { 'students':[  
                  {  
                     'termone':{  
                        'english':'fifty',
                        'science':'hundred'
                     },
                     'id':'RA1081310005'
                  }
               ]
   }

So when I do the following I get an error :

 print school ['students']['id']

TypeError: list indices must be integers, not str

Can anyone suggest how i can access the ID & where I'm going wrong!

school['students'] is a list. You are trying to access the first element of that list and id key belongs to that element. Instead, try this:

school['students'][0]['id']
Out: 'RA1081310005'

The problem here is that in your list, 'id' is not a part of a dictionary, it is part of a list. To fix this, change your dictionary to the following:

school = {'students':{
            'termone': {
                "english": "fifty:,
                "science": "hundred
            },
            "id":"RA1081310005"
        }
}

Basically, you have a list, and there is no reason to have it, so I removed it.

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