【发布时间】:2017-06-04 18:18:52
【问题描述】:
我正在尝试创建一个使用 OpenWeatherMap API 获取当前天气的程序。在从互联网接收数据时,我是编码意义上的编码新手。
我收到的错误是:
"Traceback(最近一次调用最后一次): 文件“/home/pi/Python Codes/Weather/CurrentTest3.py”,第 7 行,在 temp_k = [record['temp'] for record in url2 ['main']] #这行应该从.Json文件中记下温度信息 文件“/home/pi/Python Codes/Weather/CurrentTest3.py”,第 7 行,在 temp_k = [record['temp'] for record in url2 ['main']] #这行应该从.Json文件中记下温度信息 TypeError: 字符串索引必须是整数
我不明白为什么会这样,我的代码如下。
from dateutil import parser #imports parser
from pprint import pprint #imports pprint
import requests #imports request
url = requests.get('http://api.openweathermap.org/data/2.5/weather? q=london&APPID=APIKEY') #identifies the url address
pprint(url.json()) #prints .JSON information from address
url2 = url.json() #establishes .Json file as variable
temp_k = [record['temp'] for record in url2 ['main']] #this line should take down the temperature information from the .Json file
print(temp_k) #prints the value for temperature
【问题讨论】:
-
那是因为
url2是字典列表,而不是字典。
标签: python json string api typeerror