import json dict_data = {"name": "John", "age": 30, "city": "New York"} json_data = json.dumps(dict_data, indent=4) print(json_data)
{ "name": "John", "age": 30, "city": "New York" }
import json class Person: def __init__(self, name, age): self.name = name self.age = age class CustomEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, Person): return {"name": obj.name, "age": obj.age} return json.JSONEncoder.default(self, obj) person = Person("John", 30) json_data = json.dumps(person, cls=CustomEncoder, indent=4) print(json_data)
{ "name": "John", "age": 30 }In the above example, we have created a CustomEncoder class that extends the JSONEncoder class and overrides the default() method to customize the encoding of Objects. The JSONEncoder class is a part of the standard JSON package in Python.