Print a Python object as JSON

by default, when printing a Python object, it will show as an address to the object, like

<__main__.Student object at 0x10e430f65>

this contains only the class of the object (Student in the above example) and it memory address (0x10e430f65) and not much else. To display the content of the object in a nicely looked JSON format, we can overwrite the __str__ method of its object

import json

class Student:
  def __init__(self, name, age, school):
    self.name = name
    self.age = age
    self.school = school

  def __str__(self):
    return json.dump(self.__dict__, indent=2)