简体   繁体   English

API-TypeError:列表索引必须是整数,而不是str

[英]API - TypeError: list indices must be integers, not str

All the variables that store the API data: 所有存储API数据的变量:

formatted_data = json_data['list'][0]['main'] # Extracting the main description from the API
formatted_data3 = json_data['list'][0]['weather']['description'] # Extracting the weather description from the API
formatted_data2 = json_data['list'][0]['main']['temp'] # Extracting the temperature description from the API
formatted_data4 = json_data['list'][0]['main']['temp_min']
formatted_data5 = json_data['list'][0]['main']['temp_max']
formatted_data6 = json_data['list'][0]['clouds']['all']

Can anyone help me out with this error? 谁能帮我解决这个错误?

Traceback (most recent call last):
File "MainWeatherAPI.py", line 21, in <module>
print(ForecastAPIFunction.getForecast(city, country))
File "/home/codio/workspace/Weatherbot/ForecastAPIFunction.py", line 
13, in getForecast
formatted_data3 = json_data['list'][0]['weather']['description'] 
#Extracting the weather description from the API

EDIT: 编辑:

Code that is relevant to what I have tried so far: 与到目前为止我尝试过的代码相关的代码:

while True:
    address = input("Address: ")
    if address == 'quit' or address == 'q':
        break
    url = main_api + urllib.parse.urlencode({'address': address}) 
    json_data = requests.get(url).json() 
    #print(url)
    json_status = json_data['status'] print('API Status: ' + json_status + '\n')
    if json_status == 'OK':
        for each in json_data['results'][0]['address_components']:
            print(each['long_name'])

EDIT: 编辑:

Sample API data that correlates to all the variables that I have used to store the data. 与我用来存储数据的所有变量相关的示例API数据。 This is also relevant to the error that I am receiving. 这也与我收到的错误有关。

{
  'cnt': 40, 
  'city': {
    'name': 'Coventry', 
    'country': 'GB', 
    'id': 2652221, 
    'coord': {
      'lat': 52.4066, 
      'lon': -1.5122}
  }, 
  'message': 0.165, 
  'list': [
    {'sys': {'pod': 'n'}, 
    'dt_txt': '2017-11-23 21:00:00', 
    'weather': [
      {
        'main': 'Clouds', 
        'icon': '04n', 
        'id': 803, 
        'description': 'broken clouds'
      }
    ], 
    'rain': {}, 
    'main': {
      'temp_max': 278.37,
      'grnd_level': 1005.61, 
      'temp': 278.37, 
      'sea_level': 1018.48,
      'humidity': 79, 
      'temp_kf': 0.15, 
      'pressure': 1005.61, 
      'temp_min': 278.226}, 
      'clouds': {'all': 56}, 
      'dt': 1511470800, 
      'wind': {'deg':''}
}

try this 尝试这个

formatted_data3 = json_data['list'][0]['weather'][0]['description'] 

the weather element is array as well 天气元素也是数组

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM