Home > Enterprise >  "TypeError: list indices must be integers or slices, not str" with a the JSON file from th
"TypeError: list indices must be integers or slices, not str" with a the JSON file from th

Time:12-30

I have a problem with an scraped json file from the Air Pollution API OpenWeatherMap.

When I try to navigate through the data with aqi = air_data['list']['main']['aqi'], I get the following error: TypeError: list indices must be integers or slices, not str.

The full code is:

import requests

URL = "http://api.openweathermap.org/data/2.5/air_pollution?lat=MY_LATITUDE&lon=MY_LONGITUDE&appid=MY_API_KEY"

air_data = requests.get(URL).json()

aqi = air_data['list']['main']['aqi']

print(aqi, 'AirQualityIndex')

The air_data formatted with pprint looks like this:

{'coord': {'lat': MY_LAT, 'lon': MY_LON},
'list': [{'components': {'co': 223.64,
                      'nh3': 0.28,
                      'no': 0,
                      'no2': 5.91,
                      'o3': 42.92,
                      'pm10': 2.14,
                      'pm2_5': 1.79,
                      'so2': 1.79},
       'dt': 1640822400,
       'main': {'aqi': 1}}]}

I don't understand why it is thinking that the 1 behind 'aqi' is a string. In my other code with the Weather API it works without any problems.

CodePudding user response:

Instead of:

aqi = air_data['list']['main']['aqi']

use:

aqi = air_data['list'][0]['main']['aqi']

You didn't notice there is a list here.

  • Related