在Python中读取JSON字符串:接收错误;TypeError:字符串索引必须是整数;
我正在尝试创建一个程序,使用OpenWeatherMapAPI获取当前天气。我对从互联网上接收数据时进行编码这一意义上的编码是陌生的 我收到的错误是: “回溯(最近一次呼叫最后一次): 文件“/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:字符串索引必须是整数 我不明白为什么我得到这个,我的代码如下在Python中读取JSON字符串:接收错误;TypeError:字符串索引必须是整数;,python,json,string,api,typeerror,Python,Json,String,Api,Typeerror,我正在尝试创建一个程序,使用OpenWeatherMapAPI获取当前天气。我对从互联网上接收数据时进行编码这一意义上的编码是陌生的 我收到的错误是: “回溯(最近一次呼叫最后一次): 文件“/home/pi/Python Codes/Weather/CurrentTest3.py”,第7行,在 temp_k=[record['temp']for record in url2['main']]#这一行应该记录.Json文件中的温度信息 文件“/home/pi/Python Codes/Weath
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
数据中
main
的值是一个dict,而不是一个dict列表。因此不需要迭代它;只需直接访问临时值即可
temp_k = url2['main']['temp']
问题在于
temp_k
,记录['temp']
的这部分
这是每个变量记录的格式
:
for record in url2 ['main']:
print record
>> pressure
temp_min
temp_max
temp
humidity
您正试图将一组字符串作为字典索引,因此出现字符串索引错误。只需将temp_k
行更改为:
temp_k = [url2['main'].get('temp')]
>> [272.9]
这是因为
url2
是一个dict列表,而不是dict。