【发布时间】:2017-11-24 05:27:28
【问题描述】:
存储 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']
谁能帮我解决这个错误?
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
编辑:
与我目前尝试过的代码相关的代码:
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'])
编辑:
与我用来存储数据的所有变量相关的示例 API 数据。这也与我收到的错误有关。
{
'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':''}
}
【问题讨论】:
-
请使用 JSON 数据样例编辑您的帖子。
-
while True: address = input("Address: ") if address == 'quit' 或 address == 'q': break url = main_api + urllib.parse.urlencode({'address' : 地址}) json_data = requests.get(url).json() #print(url) json_status = json_data['status'] print('API 状态: ' + json_status + '\n') if json_status == 'OK ': for each in json_data['results'][0]['address_components']: print(each['long_name'])
-
将
[:0]更改为[0]。 -
不幸遇到同样的错误
-
@aaromated 正如我在其他评论中提到的那样。请使用来自 API 的 JSON 数据的示例输出来编辑您的帖子。调试问题会更容易。
标签: python