Question

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'
Was it helpful?

Solution

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()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top