在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_file = json.load('test.json')

但这是可行的:

f = open('test.json')
json_file = json.load(f)

其他回答

使用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)

如果你需要将字符串转换为json。然后使用loads()方法代替load()。Load()函数用于从文件中加载数据,因此使用Load()将字符串转换为json对象。

j_obj = json.loads('["label" : "data"]')

你需要先打开文件。这行不通:

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没有定义的方法,并开始寻找您毒害对象的位置。