AttributeError("'str' object has no attribute 'read'")

369,651

Solution 1

The problem is that for json.load you should pass a file like object with a read function defined. So either you use json.load(response) or json.loads(response.read()).

Solution 2

Ok, this is an old thread but. I had a same issue, my problem was I used json.load instead of json.loads

This way, json has no problem with loading any kind of dictionary.

Official documentation

json.load - Deserialize fp (a .read()-supporting text file or binary file containing a JSON document) to a Python object using this conversion table.

json.loads - Deserialize s (a str, bytes or bytearray instance containing a JSON document) to a Python object using this conversion table.

Solution 3

You need to open the file first. This doesn't work:

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

But this works:

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

Solution 4

If you get a python error like this:

AttributeError: 'str' object has no attribute 'some_method'

You probably poisoned your object accidentally by overwriting your object with a string.

How to reproduce this error in python with a few lines of code:

#!/usr/bin/env python
import json
def foobar(json):
    msg = json.loads(json)

foobar('{"batman": "yes"}')

Run it, which prints:

AttributeError: 'str' object has no attribute 'loads'

But change the name of the variablename, and it works fine:

#!/usr/bin/env python
import json
def foobar(jsonstring):
    msg = json.loads(jsonstring)

foobar('{"batman": "yes"}')

This error is caused when you tried to run a method within a string. String has a few methods, but not the one you are invoking. So stop trying to invoke a method which String does not define and start looking for where you poisoned your object.

Solution 5

AttributeError("'str' object has no attribute 'read'",)

This means exactly what it says: something tried to find a .read attribute on the object that you gave it, and you gave it an object of type str (i.e., you gave it a string).

The error occurred here:

json.load (jsonofabitch)['data']['children']

Well, you aren't looking for read anywhere, so it must happen in the json.load function that you called (as indicated by the full traceback). That is because json.load is trying to .read the thing that you gave it, but you gave it jsonofabitch, which currently names a string (which you created by calling .read on the response).

Solution: don't call .read yourself; the function will do this, and is expecting you to give it the response directly so that it can do so.

You could also have figured this out by reading the built-in Python documentation for the function (try help(json.load), or for the entire module (try help(json)), or by checking the documentation for those functions on http://docs.python.org .

Share:
369,651

Related videos on Youtube

RobinJ
Author by

RobinJ

Updated on July 31, 2021

Comments

  • RobinJ
    RobinJ almost 3 years

    In Python I'm getting an error:

    Exception:  (<type 'exceptions.AttributeError'>,
    AttributeError("'str' object has no attribute 'read'",), <traceback object at 0x1543ab8>)
    

    Given python code:

    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']
    

    What does this error mean and what did I do to cause it?

  • zakdances
    zakdances over 11 years
    I don't understand this...how does doing read() solve the problem? The response still doesn't have a read function. Are we supposed to put the string in some object with a read function?
  • Joshmaker
    Joshmaker about 11 years
    @yourfriendzak read closely, it is two different functions with very similar names. json.load() takes a file like object with a read() method, json.loads() takes a string. It's easy to miss the "s" at the end and think they are the same method.
  • Yu Shen
    Yu Shen about 11 years
    Thanks to Joshmaker's comment, json.loads() can parse string for JSON data!
  • chaim
    chaim almost 10 years
    @yourfriendzak This answer would point you that with open you can achieve that.
  • MANISH ZOPE
    MANISH ZOPE over 9 years
    Thanks Joshmaker. Your andwe is useful to me. load, loads ....How un-intuitive names given by originators of library. Really illogical
  • Karl Knechtel
    Karl Knechtel over 8 years
    @MANISHZOPE the s stands for "string". I agree that the standard library has some serious issues overall with how things are named, and this is a good example of how it gets messed up.
  • Rishav
    Rishav over 5 years
    @kosii I request you to what @Joshmaker said in your answer. It would be more helpful to users who just tent to overlook that tiny s
  • Arthur Attout
    Arthur Attout almost 5 years
    I hope the person who thought json.loads was more self-explanatory than json.load_string has been fired right after the release.
  • Karl Knechtel
    Karl Knechtel over 4 years
    That's what OP called it. I'm always on the fence about whether to change or preserve such identifier names when helping others. :/
  • Andrea Ligios
    Andrea Ligios over 4 years
    Oh, you're right, I've skimmed it... I wasn't complaining, though :)
  • Nitin Khanna
    Nitin Khanna about 4 years
    I found the error in the question when trying to open a file instead of a request response in the question. Clearly, at the backend, json is treating both similarly, and so this answer helped me. Clearly worth an upvote.
  • Amir Md Amiruzzaman
    Amir Md Amiruzzaman over 3 years
    "loads" worked for me. Thank you for your solution