在 Python 中,我收到一个错误:
Exception: (<type 'exceptions.AttributeError'>,
AttributeError("'str' object has no attribute 'read'",), <traceback object at 0x1543ab8>)
给定python代码:
def getEntries (self, sub):
url = 'http://www.reddit.com/'
if (sub != ''):
url += 'r/' + sub
request = urllib2.Request (url +
'.json', None, {'User-Agent' : 'Reddit desktop client by /user/RobinJ1995/'})
response = urllib2.urlopen (request)
jsonStr = response.read()
return json.load(jsonStr)['data']['children']
这个错误是什么意思,我做了什么导致它?
问题是对于 json.load
,您应该传递一个定义了 read
函数的文件,如对象。因此,您可以使用 json.load(response)
或 json.loads(response.read())
。
好的,这是一个旧线程但是。我有同样的问题,我的问题是我使用 json.load
而不是 json.loads
这样,json 加载任何类型的字典都没有问题。
json.load - 使用此转换表将 fp(支持 .read() 的文本文件或包含 JSON 文档的二进制文件)反序列化为 Python 对象。 json.loads - 使用此转换表将 s(包含 JSON 文档的 str、bytes 或 bytearray 实例)反序列化为 Python 对象。
您需要先打开文件。这不起作用:
json_file = json.load('test.json')
但这有效:
f = open('test.json')
json_file = json.load(f)
如果您收到这样的 python 错误:
AttributeError: 'str' object has no attribute 'some_method'
您可能通过用字符串覆盖您的对象而意外毒害了您的对象。
如何用几行代码在python中重现这个错误:
#!/usr/bin/env python
import json
def foobar(json):
msg = json.loads(json)
foobar('{"batman": "yes"}')
运行它,它会打印:
AttributeError: 'str' object has no attribute 'loads'
但是更改变量名的名称,它工作正常:
#!/usr/bin/env python
import json
def foobar(jsonstring):
msg = json.loads(jsonstring)
foobar('{"batman": "yes"}')
当您尝试在字符串中运行方法时会导致此错误。 String 有一些方法,但不是您要调用的方法。因此,停止尝试调用 String 未定义的方法,并开始寻找您毒害对象的位置。
AttributeError("'str' object has no attribute 'read'",)
这正是它所说的:某物试图在您给它的对象上找到一个 .read
属性,而您给它一个 str
类型的对象(即,您给它一个字符串)。
错误发生在这里:
json.load (jsonofabitch)['data']['children']
好吧,您不是在任何地方寻找 read
,因此它必须发生在您调用的 json.load
函数中(如完整回溯所示)。这是因为 json.load
试图 .read
您给它的东西,但您给了它 jsonofabitch
,它当前命名了一个字符串(您通过在 response
上调用 .read
创建)。
解决方案:不要自己调用.read
;该函数将执行此操作,并希望您直接给它 response
以便它可以这样做。
您也可以通过阅读函数的内置 Python 文档(尝试 help(json.load)
,或整个模块的文档(尝试 help(json)
)或查看 http://docs.python.org 上的这些函数的文档)来了解这一点。
代替 json.load() 使用 json.loads() 它会起作用:例如:
import json
from json import dumps
strinjJson = '{"event_type": "affected_element_added"}'
data = json.loads(strinjJson)
print(data)
所以,不要使用 json.load(data.read())
使用 json.loads(data.read())
:
def findMailOfDev(fileName):
file=open(fileName,'r')
data=file.read();
data=json.loads(data)
return data['mail']
不定期副业成功案例分享
json.load()
使用read()
方法获取类似文件的对象,json.loads()
获取字符串。很容易错过最后的“s”,并认为它们是相同的方法。open
您可以实现这一目标。s
代表“字符串”。我同意标准库在命名事物方面存在一些严重的问题,这是一个很好的例子,说明它是如何被搞砸的。