Python; urllib error: AttributeError: 'bytes' object has no attribute 'read'

Parseltongue picture Parseltongue · Jul 1, 2011 · Viewed 101.8k times · Source

Note: This is Python 3, there is no urllib2. Also, I've tried using json.loads(), and I get this error:

TypeError: can't use a string pattern on a bytes-like object

I get this error if I use json.loads() and remove the .read() from response:

TypeError: expected string or buffer

>

import urllib.request
import json

response = urllib.request.urlopen('http://www.reddit.com/r/all/top/.json').read()
jsonResponse = json.load(response)

for child in jsonResponse['data']['children']:
    print (child['data']['title'])

Does not work... I have no idea why.

Answer

MRAB picture MRAB · Jul 1, 2011

Try this:

jsonResponse = json.loads(response.decode('utf-8'))