OpenWeather API JSON



我从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"]

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

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

如果你只想从列表中的一个特定项目中获得变量,你应该使用

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

最新更新