Home > other >  OpenWeather API JSON
OpenWeather API JSON

Time:11-11

I've JSON file returned from API. And i need to access one variable but it's inside JSON inside list. I've tried some things but none worked. I'm using python and json module.

{
  "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"]

CodePudding user response:

If you want to access the same variable for each element in the list you need to use

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

If you just want the variable from one specific item in the list you should use

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