26

I'm trying to convert a string, generated from an http request with urllib3.

Traceback (most recent call last):
  File "<pyshell#16>", line 1, in <module>
    data = json.load(data)
  File "C:\Python27\Lib\json\__init__.py", line 286, in load
    return loads(fp.read(),
AttributeError: 'str' object has no attribute 'read'

>>> import urllib3
>>> import json
>>> request = #urllib3.request(method, url, fields=parameters)
>>> data = request.data

Now... When trying the following, I get that error...

>>> json.load(data) # generates the error
>>> json.load(request.read()) # generates the error

Running type(data) and type(data.read()) both return <type 'str'>

data = '{"subscriber":"0"}}\n'
6
  • 2
    Your JSON has an extra bracket. Is that intentional? Commented May 16, 2013 at 1:33
  • What do you mean "Convert string to JSON"? JSON is a string format. You want to convert JSON to the appropriate native Python objects (in this case a dict mapping one string to another)? Or some non-JSON string into a JSON string, or something different? Commented May 16, 2013 at 1:34
  • 1
    type(data.read()) shouldn't work if data is a string. Commented May 16, 2013 at 1:35
  • In fact, type(data.read()) is guaranteed to raise the exact same exception as json.load(data). I think he meant type(request.read()), which will successfully return the str type. Commented May 16, 2013 at 1:36
  • The extra bracket was a typo. Sorry about that. The data.read() was a typo. Commented May 16, 2013 at 2:07

1 Answer 1

51

json.load loads from a file-like object. You either want to use json.loads:

json.loads(data)

Or just use json.load on the request, which is a file-like object:

json.load(request)

Also, if you use the requests library, you can just do:

import requests

json = requests.get(url).json()
Sign up to request clarification or add additional context in comments.

4 Comments

Or, instead of turning json.load(request.read()) into json.loads(request.read()), just call json.load(request).
I am using the requests library, though it is currently commented out. Working on Google Apps Engine which wasn't allowing me to run it, and urlfetch was having issues on the same GET request. So, they support raw urllib3 and that's what I'm testing with. json.loads(request.data) is wokring, json.load(request) does not. Thanks for the help.
` json = requests.get(url).json()` did not work for me as well my original line of code pageContent = requests.get(url,verify=False).json()
Limitation: the data parameter a=has to be <= 1GB, otherwise it will fail

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.