If you are asking about vanilla Python, serialization could be done this way:
import json
class Person:
def __init__(self, name, age, city):
self.name = name
self.age = age
self.city = city
def to_json(self):
return json.dumps(self, default=lambda o: o.__dict__)
person = Person("John", 30, "New York")
print(person.to_json())
So we're just converting an object to a dict using __dict__ attribute.
But if you need something more sophisticated, you might need DRF (Django REST Framework) or pydantic. An example how it could be done with DRF:
from rest_framework import serializers
from rest_framework.serializers import Serializer
class Person:
def __init__(self, name, age, city):
self.name = name
self.age = age
self.city = city
class PersonSerializer(Serializer):
name = serializers.CharField()
age = serializers.IntegerField()
city = serializers.CharField()
def create(self, validated_data):
return Person(**validated_data)
person = Person("John", 30, "New York")
print(PersonSerializer(person).data)
This way you have a much better control over it. See docs.
jsonmodule only knows how to serialize built-in types. Look atjson.JSONEncoderto see how to serialize instances of your own classes.