解析JSON时出现问题



我正在尝试使用Pokeapi来创建pokedex的快速版本。我只想让用户输入一个pokemon名称,并返回他们选择的pokemon的名称和其他小细节。我可以让我的代码打印出pokemon的整个json文件,但不仅仅是特定信息。我使用的是Python 3。

我当前的代码如下:

import requests
import pprint

def main():
poke_base_uri = "https://pokeapi.co/api/v2/pokemon/"
poke_choice = "pidgey"
pokeresponse = requests.get(f"{poke_base_uri}{poke_choice}/")
# Decode the response
poke = pokeresponse.json()
pprint.pprint(poke)
print("nGreat Choice you chose:")
for name in poke:
name_info = poke.get(pokemon_species)
print(name_info.json().get('name'))

看起来你已经非常接近了。

我会先删除for循环。你不需要这个。

poke确实包含您要查找的所有信息,但您需要将参数更改为poke.get。如果你打印出poke.keys(),它会显示dict拥有的所有密钥。你应该看到这样的东西:

dict_keys(['abilities', 'base_experience', 'forms', 'game_indices', 'height', 'held_items', 'id', 'is_default', 'location_area_encounters', 'moves', 'name', 'order', 'species', 'sprites', 'stats', 'types', 'weight'])

我想你想做的是:

>>> name_info = poke.get("species")
{'name': 'pidgey', 'url': 'https://pokeapi.co/api/v2/pokemon-species/16/'}

您也不需要再调用.json((,它们实际上在name_info对象上不可用。.json是requests-response对象的一个属性(当您调用requests.get时得到的(。它返回一个包含站点请求数据的python字典。因为它返回一个普通的python dict,所以您可以使用.get.访问它的所有键和值

我建议你多读一些python词典。它们是一个非常强大的对象,学会使用它们对于编写漂亮的python至关重要。

https://docs.python.org/3/library/stdtypes.html?highlight=dict#dict

最新更新