【问题标题】:OpenWeather API JSON开放天气 API JSON
【发布时间】:2021-12-23 00:41:15
【问题描述】:

我有从 API 返回的 JSON 文件。我需要访问一个变量,但它在 JSON 内部列表中。我已经尝试了一些东西,但没有奏效。我正在使用 python 和 json 模块。

{
  "list": [
    {
      "dt": 1636318800,
      "main": {
        "temp": 281.07,
        "feels_like": 277.81,
        "temp_min": 280.86,
        "temp_max": 281.07,
        "pressure": 1014,
        "sea_level": 1014,
        "grnd_level": 987,
        "humidity": 72,
        "temp_kf": 0.21
      },
      "weather": [
        {
          "id": 804,
          "main": "Clouds",
          "description": "overcast clouds",
          "icon": "04n"
        }
      ],
      "clouds": {
        "all": 97
      },
      "wind": {
        "speed": 5.85,
        "deg": 242,
        "gust": 10.34
      },
      "visibility": 10000,
      "pop": 0.17,
      "sys": {
        "pod": "n"
      },
      "dt_txt": "2021-11-07 21:00:00"
    }]
}
with open("test.json") as json_file:
    data = json.load(json_file)
    for p in data[list]["main"]:
        temps = p["temp_min"]

【问题讨论】:

  • 试试这个数据["list"][0]["main"]["temp_min"]
  • 您是否尝试使用调试器单步执行?还是记录?也许你会得到这个问题的答案,但你真的应该学习基本的开发技术。 stackoverflow.com/q/6579496/109941

标签: python json api


【解决方案1】:

如果你想为列表中的每个元素访问相同的变量,你需要使用

for p in data[list]:
    temps = p["main"]["temp_min"]
    # do something with temps var...

如果您只想要列表中某个特定项目的变量,您应该使用

temps = data[list][0]["main"]["temp_min"]

【讨论】:

  • 它工作正常。非常感谢您的帮助
猜你喜欢
  • 2015-02-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多