To modify the way your class is encoded into JSON format/get rid of Login prefix, you could use one of two different parameters for json.dumps():
- Extending JSONEncoder (recommended)
To use a custom JSONEncoder subclass (e.g. one that overrides the
default() method to serialize additional types), specify it with the
cls kwarg; otherwise JSONEncoder is used.
class ComplexEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, Login):
return {"request_type": obj.request_type, "username": obj.username, "password": obj.password}
json.dumps(authorized_user, cls=ComplexEncoder)
# {"request_type": "1", "username": "test", "password": "test2"}
- default param
If specified, default should be a function that gets called for objects that can’t otherwise be serialized. It should return a JSON encodable version of the object or raise a TypeError. If not specified, TypeError is raised.
def new_encoder(obj):
if isinstance(obj, Login):
return {"request_type": obj.request_type, "username": obj.username, "password": obj.password}
json.dumps(authorized_user, default=new_encoder)
# {"request_type": "1", "username": "test", "password": "test2"}
Reference: https://docs.python.org/3/library/json.html
{k.split("__")[1]:v for k,v in vars(authorised_user)}