Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between json.JSONDecoder().decode() and json.loads()

Tags:

python

json

I am using urllib2 to grab the html of a url and then a regex to extract a JSON that I need from there. I want to get the usual "dictionary of dictionaries" Python object and both of the following work:

my_json #a correctly formatted json string
json_dict1 = json.JSONDecoder().decode(my_json)
json_dict2 = json.loads(my_json)

What is the difference and which is better in what circumstances (besides mine, but that one in particular)?

like image 886
kilgoretrout Avatar asked Feb 04 '15 17:02

kilgoretrout


1 Answers

json.loads() essentially creates a json.JSONDecoder() instance and calls decode on it. As such your first line is exactly the same thing as the second line. See the json.loads() source code.

The module offers you flexibility; a simple function API or a full OO API that you can subclass if needed.

like image 64
Martijn Pieters Avatar answered Sep 24 '22 02:09

Martijn Pieters