AttributeError: 'tuple' object has no attribute 'read' when reading from JSON data

AttributeError: 'tuple' object has no attribute 'read' when reading from JSON data

所以,这很奇怪。我正在尝试在我的 RaspberryPi 上获取 运行 的脚本,以从来自 weathe运行derground 的 JSON 流中获取天气数据。我正在 Python3.5 工作,在最新的 Raspbian-Stretch OS 上开发新的 Raspberry Pi。它在其他机器上 运行ning 时有效(windows 通过 VisualStudio 和另一个 Raspberry Pi 运行ning 相同的发行版和 LEDES 发行版上的 Onion Omega2)

我正在阅读的行(根据本网站上的其他搜索编辑)是:

import urllib.request
import json

# Get and load the weather data from my house weather station.
weatherdata = urllib.request.urlretrieve("http://api.wunderground.com/api/<myAPIKey-hidden here>/conditions/q/pws:KKYLOUIS68.json")
weatherinfo = json.loads(weatherdata.read())

来自 shell 的 return 是这样的:

Traceback (most recent call last):
  File "/home/pi/myweather_win.py", line 18, in <module>
    weatherinfo = json.loads(weatherdata.read())
AttributeError: 'tuple' object has no attribute 'read'

我不是程序员,只是想学习,这让我很困惑,因为它在其他系统上工作。

使用urlopen代替urlretrieve

weatherdata = urllib.request.urlopen("http://api.wunderground.com/api/c8659b546235193f/conditions/q/pws:KKYLOUIS68.json")
json.loads(weatherdata.read())

正如 RafaelC 所说,您应该改用 urlopen。 但是,RafaelC 的代码有问题。 由于我无法对他的回答添加评论,因此我 post 将其作为回答。 weatherdata.read() returns 字节对象而不是字符串, 所以我们必须用 .decode():

来转换它
weatherdata = urllib.request.urlopen("http://api.wunderground.com/api/c8659b546235193f/conditions/q/pws:KKYLOUIS68.json")
content = weatherdata.read()
json.loads(content.decode())

测试于:Python 3.4.9、CentOS 7.6.1810