猿问

AttributeError: 'tuple' 对象在从 JSON 数据读取时没有属性 'read'

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


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


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())

从外壳返回是这样的:


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'

我不是程序员,只是想学习,这让我很难过,因为它可以在其他系统上运行。


MMMHUHU
浏览 224回答 2
2回答

三国纷争

正如 RafaelC 所说,你应该urlopen改用。但是,RafaelC 的代码有问题。由于我无法在他的答案中添加评论,因此我将其发布为答案。 weatherdata.read()返回字节对象而不是字符串,因此我们必须将其转换为.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

GCT1015

使用urlopen代替urlretrieveweatherdata = urllib.request.urlopen("http://api.wunderground.com/api/c8659b546235193f/conditions/q/pws:KKYLOUIS68.json")json.loads(weatherdata.read())
随时随地看视频慕课网APP

相关分类

Python
我要回答