Capture Json information using Python

Asked

Viewed 193 times

1

I am working with the SWAPI API with Python and find the following difficulty: When I get the information from a Json, Dict is returned when I access the key search, I get a list, but I cannot get the 'name' contained in it.

import requests
import sys
import json

nome = 'Tatooine'
url = 'https://swapi.co/api/planets/'
resp = requests.get(url, params={'search': nome})

if resp.status_code != 200:
    # This means something went wrong.
    raise resp.__getstate__('GET /planets/1 {}'.format(resp.status_code))


planeta = resp.json()
print(type(planeta))
print(planeta.keys())
print(type(planeta['results']))

x = planeta['results'][0]

print(x)

Here is what is obtained with the code

<class 'dict'>
dict_keys(['count', 'next', 'previous', 'results'])
<class 'list'>
{'name': 'Tatooine', 'rotation_period': '23', 'orbital_period': '304', 'diameter': '10465', 'climate': 'arid', 'gravity': '1 standard', 'terrain': 'desert', 'surface_water': '1', 'population': '200000', 'residents': ['https://swapi.co/api/people/1/', 'https://swapi.co/api/people/2/', 'https://swapi.co/api/people/4/', 'https://swapi.co/api/people/6/', 'https://swapi.co/api/people/7/', 'https://swapi.co/api/people/8/', 'https://swapi.co/api/people/9/', 'https://swapi.co/api/people/11/', 'https://swapi.co/api/people/43/', 'https://swapi.co/api/people/62/'], 'films': ['https://swapi.co/api/films/5/', 'https://swapi.co/api/films/4/', 'https://swapi.co/api/films/6/', 'https://swapi.co/api/films/3/', 'https://swapi.co/api/films/1/'], 'created': '2014-12-09T13:50:49.641000Z', 'edited': '2014-12-21T20:48:04.175778Z', 'url': 'https://swapi.co/api/planets/1/'}
PS C:\Users\thiag\OneDrive\Documentos\Desenvolvimento\star_wars\__init__.py\src>

I need the code to return only to value Tatooine.

2 answers

1


Note that the data type of planeta['results'][0] is a dictionary. This means, that I can then search for the ['name'] key (which is the one holding the value Tatooine).

x = planeta['results'][0]['name']
print(x)

1

I ended up finding another possible solution:

planeta = resp.json()
valor = planeta['results'][0]
print(planeta.keys())
print(f'Repository name: {valor["name"]}')

Browser other questions tagged

You are not signed in. Login or sign up in order to post.