Python

Python

By DeepSource

Unnecessary use of json.loads() for file data PY-W0078

Anti-pattern
Major
Autofix

The json module provides two ways to read JSON data: a .loads() method that accepts a JSON string, and a .load() method, that works on files directly. So instead of reading a file manually and passing it to json.loads(), it is recommended to use json.load() directly.

Bad practice

with open('data.json') as file:
    data = json.loads(file.read())  # Reading file manually

class Socket:
    def read_json(self, data):
        json.loads(self.socket.read())  # Reading socket manually
        self.socket.close()

Recommended

with open('data.json') as file:
    data = json.load(file)  # Directly passing the file object

class Socket:
    def read_json(self, data):
        json.load(self.socket)  # Directly passing the socket object
        self.socket.close()