Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 381
Parseltongue Avatar asked Jun 30 '11 22:06

Parseltongue


3 Answers

Try this:

jsonResponse = json.loads(response.decode('utf-8'))
like image 105
MRAB Avatar answered Nov 16 '22 21:11

MRAB


Use json.loads not json.load.

(load loads from a file-like object, loads from a string. So you could just as well omit the .read() call instead.)

like image 39
Katriel Avatar answered Nov 16 '22 21:11

Katriel


I'm not familiar with python 3 yet, but it seems like urllib.request.urlopen().read() returns a byte object rather than string.

You might try to feed it into a StringIO object, or even do a str(response).

like image 2
Dog eat cat world Avatar answered Nov 16 '22 23:11

Dog eat cat world