59

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.

2
  • in what way doesn't it work? try urllib2.urlopen instead Commented Jun 30, 2011 at 22:28
  • I saved a lot of headaches by using the http.client: docs.python.org/3/library/http.client.html#examples Commented Feb 27, 2015 at 18:13

4 Answers 4

107

Try this:

jsonResponse = json.loads(response.decode('utf-8'))
Sign up to request clarification or add additional context in comments.

3 Comments

For me, it was json.loads(request.body.decode('utf-8'))
it this bug in only 3.5 version ?
I have got error
46

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.)

1 Comment

Does not work. If you include the .read, this error is prompted: TypeError: can't use a string pattern on a bytes-like object If you remove the .read(), you get this error: TypeError: expected string or buffer
2

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).

Comments

0

I got the same error {AttributeError: 'bytes' object has no attribute 'read'} in python3. This worked for me later without using json:

from urllib.request import urlopen
from bs4 import BeautifulSoup

url = 'https://someurl/'
page = urlopen(url)
html = page.read()
soup = BeautifulSoup(html)
print(soup.prettify('latin-1'))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.