0

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 i.e(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" i.e title,first,last

I tried

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

Error: index out of bound

1
  • Use quotes to access the name field : data['results'][1]['name'][0]. Here you are trying to use the name variable instead of a string. Commented Jan 9, 2020 at 19:19

2 Answers 2

2

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']
Sign up to request clarification or add additional context in comments.

Comments

1

name needs to be in quotations.

Change from this format.

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

To this

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

6 Comments

But the list has only one element
@shaswatkumar did this work? ans = data['results'][0]['name']['first']
Okay, but there are more changes I have made than just the typo, please do try it.
There is no ['name'][0]. As such, this answer is correct (as is @ekneiling's)
But how are we accessing 'name' i.e 1st index using [0] i.e same as 'gender'
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.