Learner
Learner

Reputation: 393

What is the difference between json() method and json.loads()

I was practicing python with json data. I came across .json() method and json.loads(). Both returned the same output.I was wondering if there is any difference between these two.

r = request.get('name of url')
text = r.text
data = json.loads(text)

r = request.get('name of url')
data1 = r.json()

Both data and data1 has a same type "dict" and returns the same output. Why should we use one vs other? Any insights is appreciated.

Upvotes: 12

Views: 7649

Answers (4)

blackraven
blackraven

Reputation: 5597

There are 2 slight differences.

  1. The inputs are different. Assuming r = requests.get(...),

    the r.json() outputs type dict, but takes in type requests.models.Response.

    the json.loads(r.text) outputs type dict, but takes in type string.

  2. The encoding assumptions are different:

    The r.json() goes through additional step to detect the encoding before processing the input, more details here.

    The json.loads(r.text) assumes the default encoding to be 'UTF-8' and process the input.

In conclusion, if you are sure the input is 'UTF-8' encoded, use json.loads(r.text). For more a robust way without the need to check for encoding, use r.json() (I personally prefer this).

Upvotes: 3

zvone
zvone

Reputation: 19352

The json method of requests.models.Response objects ends up calling the json.loads method, but it may do something more.

You can see in the requests.models.Response.json source code that it sometimes tries to guess the encoding prior to calling complexjson.loads (which is in fact json.loads):

    if not self.encoding and self.content and len(self.content) > 3:
        # No encoding set. JSON RFC 4627 section 3 states we should expect
        # UTF-8, -16 or -32. Detect which one to use; If the detection or
        # decoding fails, fall back to `self.text` (using chardet to make
        # a best guess).
        encoding = guess_json_utf(self.content)

So, it seems that it is in general probably better to use r.json() than json.loads(r.text).

Upvotes: 8

phi
phi

Reputation: 11704

.json is a method of requests.models.Response class. It returns json body data from the request's response.

import requests
r = requests.get('https://reqres.in/api/users?page=2')
print(type(r))  # <class 'requests.models.Response'>
r.json() 

loads is a function from json package to parse string data

import json
print(type(r.text)) # <class 'str'>
json.loads(r.text)

json.loads can be used with any string data, not only in requests context

json.loads('{"key": "value"}')

Upvotes: 3

Arash Hatami
Arash Hatami

Reputation: 5541

The .json() is a shortcut of json.loads()

There is many methods for json in python

load()
loads()
dump()
dumps()

Read about difference here

Upvotes: 1

Related Questions