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'
you can turn it into JSON in Python using the json. loads() function. The json. loads() function accepts as input a valid string and converts it to a Python dictionary.
String data can be easily converted to JSON using the stringify() function, and also it can be done using eval() , which accepts the JavaScript expression that you will learn about in this guide.
JavaScript Object Notation (JSON) is a standardized format commonly used to transfer data as text that can be sent over a network. It's used by lots of APIs and Databases, and it's easy for both humans and machines to read. JSON represents objects as name/value pairs, just like a Python dictionary.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With