Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string to JSON in Python?

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'
like image 942
bnlucas Avatar asked May 16 '13 01:05

bnlucas


People also ask

How do you convert string to JSON in Python?

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.

How do I convert a string to JSON?

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.

What is JSON () in Python?

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.


1 Answers

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()
like image 185
Blender Avatar answered Oct 10 '22 11:10

Blender