Reputation: 393
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
Reputation: 5597
There are 2 slight differences.
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
.
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
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
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
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