Kelvin de Reus
Kelvin de Reus

Reputation: 1

How to read data from a list in a json object

I have JSON data that I need to read and then print:

json_load =\
{"city": {"coord": {"lat": 52.2183, "lon": 6.8958},
          "country": "NL",
          "id": 2756071,
          "name": "Enschede",
          "population": 153655,
          "sunrise": 1656472443,
          "sunset": 1656532643,
          "timezone": 7200},
 "cnt": 40,
 "cod": "200",
 "list": [{"clouds": {"all": 50},
           "dt": 1656536400,
           "dt_txt": "2022-06-29 21:00:00",
           "main": {"feels_like": 295.23,
                    "grnd_level": 1007,
                    "humidity": 60,
                    "pressure": 1012,
                    "sea_level": 1012,
                    "temp": 295.38,
                    "temp_kf": 2.77,
                    "temp_max": 295.38,
                    "temp_min": 292.61},
           "pop": 0,
           "sys": {"pod": "n"},
           "visibility": 10000,
           "weather": [{"description": "scattered clouds",
                        "icon": "03n",
                        "id": 802,
                        "main": "Clouds"}],
           "wind": {"deg": 99, "gust": 1.93, "speed": 1.9}}]}

Now I want to read: feels_like, temp, etc. I can read the first part on top with:

print(json_load['city']['coord'])

But if I want to read:

print(json_load['list']['main'])

I get a keyword error 0.

Upvotes: 0

Views: 80

Answers (1)

martineau
martineau

Reputation: 123463

Since json_load['list'] is a list, you have to use indices to access the items in it. Here's how to get the contents of the first (zeroth) element of it:

print(json_load['list'][0]['main']['feels_like'])  # -> 295.23
print(json_load['list'][0]['main']['temp'])  # -> 295.38

Upvotes: 3

Related Questions