【问题标题】:Reading a JSON string in Python: Receiving error " TypeError: string indices must be integers"在 Python 中读取 JSON 字符串:接收错误“TypeError:字符串索引必须是整数”
【发布时间】: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


【解决方案1】:

问题在于temp_krecord['temp'] 的这一部分。

这是每个变量record的格式:

for record in url2 ['main']:
    print record

>> pressure
temp_min
temp_max
temp
humidity

您尝试将一堆字符串作为字典进行索引,因此出现字符串索引错误。只需将temp_k 行更改为:

temp_k = [url2['main'].get('temp')]

>> [272.9]

【讨论】:

    【解决方案2】:

    您数据中main 的值是一个字典,而不是字典列表。所以不需要遍历它;只需直接访问 temp 值。

    temp_k = url2['main']['temp'] 
    

    【讨论】:

      猜你喜欢
      • 2015-03-06
      • 1970-01-01
      • 2016-08-26
      • 2021-09-11
      • 1970-01-01
      • 1970-01-01
      • 2014-12-30
      • 2020-06-24
      • 1970-01-01
      相关资源
      最近更新 更多