在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()使用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']

如果你得到一个这样的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没有定义的方法,并开始寻找您毒害对象的位置。

好吧,这是一个旧的帖子,但是。 我也有同样的问题,我的问题是我使用了json。Load而不是json.loads

这样,json加载任何类型的字典都没有问题。

官方文档

json。load -使用此转换表将fp(支持.read()的文本文件或包含JSON文档的二进制文件)反序列化为Python对象。 json。loads -使用此转换表将s(包含JSON文档的str, bytes或bytearray实例)反序列化为Python对象。

使用json.loads()函数,将s放在后面…只是一个错误,顺便说一下,我在搜索错误后才意识到

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.loads(jsonStr)['data']['children']

试试这个

首先以文本文件的形式打开该文件

json_data = open("data.json", "r")

现在把它载入字典

dict_data = json.load(json_data)