kilgoretrout
kilgoretrout

Reputation: 3657

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

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)?

Upvotes: 7

Views: 3141

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1125398

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.

Upvotes: 9

Related Questions