【问题标题】:Trying to extract nested json data into a vertical list [closed]试图将嵌套的json数据提取到垂直列表中[关闭]
【发布时间】:2021-06-13 13:15:45
【问题描述】:

如何从这个 url 中提取所有的坦克名称 (https://api.wotblitz.com/wotb/encyclopedia/vehicles/?application_id=e079b7fe335c9af4749be776fbf5fc2b&nation=usa) 并将它们显示为垂直列表?

仅供参考,我刚刚在过去 40 小时内开始编写代码来解决这个问题。我知道正确的解决方案是从 6 个月的 python 速成课程开始,但我真的很想通过解决这个问题来学习。任何建议的代码将不胜感激。 谢谢,

【问题讨论】:

  • 欢迎来到 SO。这不是讨论论坛或教程。请使用tour 并花时间阅读How to Ask 以及该页面上的其他链接。花一些时间与the Tutorial 练习示例。它将让您了解 Python 提供的帮助您解决问题的工具。
  • 关闭的原因在这里有点误导。我们曾经有一个“过于宽泛”的密切原因,其中包括“未能表现出对概念的基本理解”;但是新的(-ish)“需要更多关注”更具体地涉及许多问题。更正确的关闭原因现在是“需要细节或清晰度”。

标签: python json python-requests pycharm


【解决方案1】:

这是使用“列表推导”从坦克列表中提取名称的建议。

import requests

response = requests.get('https://api.wotblitz.com/wotb/encyclopedia/vehicles/?application_id=e079b7fe335c9af4749be776fbf5fc2b&nation=usa')
j = response.json()

tanks = j['data'].values()
names = [tank['name'] for tank in tanks]  # list comprehension

print(names)

【讨论】:

  • 哇,非常感谢你们!我很高兴我走在了正确的道路上,但你的回应是如此优雅和高效。我迫不及待想了解更多 Python!
【解决方案2】:

这段代码可以做到。由于您是初学者,因此我添加了一些 cmets 试图解释代码的作用。 您还可以进一步检查以下概念:

  • REST API
  • Python 请求模块
  • Python 数据结构(这里主要使用字典)

示例代码:

import requests # library to interact with HTTP

# Get the data
response = requests.get('https://api.wotblitz.com/wotb/encyclopedia/vehicles/?application_id=e079b7fe335c9af4749be776fbf5fc2b&nation=usa')
# Transform the reponse in python dictionary
data_from_api = response.json()

# Get only the part of data for which we care
tanks = data_from_api.get("data")

tank_names = [] # initialize empty list

# Tanks are now a dictionary as well.
# we want to get all the keys and all the values from them
# and from the values (also dictionaries) we want to extract the name value
for tank, specs in tanks.items():
    
    tank_names.append(specs.get("name"))
print(tank_names)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-06
    • 2021-09-03
    • 2020-10-24
    • 2018-05-12
    • 2021-09-05
    相关资源
    最近更新 更多