Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

json

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.

like image 466
Learner Avatar asked Sep 22 '19 11:09

Learner


2 Answers

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

like image 191
zvone Avatar answered Sep 30 '22 06:09

zvone


.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"}')
like image 31
phi Avatar answered Sep 30 '22 06:09

phi