简体   繁体   中英

Parsing JSON data in Python

This is the json file I want to parse

{
    "results": [
        {
            "gender": "male",
            "name": {
                "title": "mr",
                "first": "brad",
                "last": "gibson"
            },
            "location": {
                "street": "9278 new road",
                "city": "kilcoole",
                "state": "waterford",
                "postcode": "93027",
                "coordinates": {
                    "latitude": "20.9267",
                    "longitude": "-7.9310"
                }
            },
            "picture": {
                "large": "https://randomuser.me/api/portraits/men/75.jpg",
                "medium": "https://randomuser.me/api/portraits/med/men/75.jpg",
                "thumbnail": "https://randomuser.me/api/portraits/thumb/men/75.jpg"
            }
        }
    ]
}

I can easily access the first element ie(gender) using

 response = requests.get('https://randomuser.me/api')
 data = response.json()

 ans = data['results'][0]['gender']
 print(ans)

but I am not getting how to access elements of "name" ie title,first,last

I tried

ans = data['results'][1]['name'][0]['title']

Error: index out of bound

It looks like there's only one result, so use the same index as you did for gender. Also, name is a dict not a list

ans = data['results'][0]['name']['title']

name needs to be in quotations.

Change from this format.

ans = data['results'][1][name][0]

To this

ans = data['results'][0]['name']['first']

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