【问题标题】:AttributeError: 'tuple' object has no attribute 'read' when reading from JSON dataAttributeError:从 JSON 数据读取时,“元组”对象没有“读取”属性
【发布时间】:2019-02-22 01:45:07
【问题描述】:

所以,这很奇怪。我正在尝试让一个脚本在我的 RaspberryPi 上运行,以从 weatherunderground 的 JSON 流中获取天气数据。我在最新的 Raspbian-Stretch OS 上使用 Python3.5 开发新的 Raspberry Pi。它在其他机器上运行时工作(通过 VisualStudio 的 Windows 和另一个运行相同发行版的 Raspberry Pi 和 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 的返回是这样的:

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'

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

【问题讨论】:

    标签: python json python-3.x tuples urllib


    【解决方案1】:

    正如 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

    【讨论】:

    • 谢谢,现在可以了。现在我需要清理来自 JSON 的一些调用。但它正在阅读和格式化,因为我现在需要它。谢谢,大时代。对我来说未来有很多学习。
    • 再次感谢。正确拉入的所有内容现在在其中一行中有一个额外的“)”。现在,开始添加 LCD 调用以将数据打印到 LCD,并最终进行电子纸显示。
    【解决方案2】:

    使用urlopen 代替urlretrieve

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

    【讨论】:

    • 现在我得到以下信息: Traceback(最近一次调用最后一次):文件“/home/pi/myweather_win.py”,第 16 行,在 weatherinfo = json.loads(weatherdata. read()) 文件“/usr/lib/python3.5/json/__init__.py”,第 312 行,加载 s.__class__.__name__)) 类型错误:JSON 对象必须是 str,而不是 'bytes'
    • @AdventuresOfRaven 请确保完全运行这些代码行。无法重现您的错误;)
    • 那么如何将 JSON 数据添加到变量中呢?我实际上为不同的数据集调用了 3 个不同的 URL,以便在屏幕(后来的 LCD)上读取和写入我需要的内容。我必须把 json.loads(weatherdata.read()) 放在某个地方。就像我说的,它适用于其他设置,只是不适用于这个 Pi。
    • 我试过用 python3 和 python3.5 运行它。 Python2 和 Python2.7 仍然给出原始错误。我会继续挖掘。
    猜你喜欢
    • 1970-01-01
    • 2021-02-26
    • 1970-01-01
    • 2020-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多