we could just serialize the __dict__ attributec contact("john""smith"json dumps( __dict__'{"last""smith""first""john"}but accessing special (double-underscoreattributes in this fashion is kind of crude alsowhat if the receiving code (perhaps some javascript on web pagewanted that full_name property to be suppliedof coursewe could construct the dictionary by handbut let' create custom encoder insteadimport json class contactencoder(json jsonencoder)def default(selfobj)if isinstance(objcontact)return {'is_contact'true'first'obj first'last'obj last'full'obj full_namereturn super(default(objthe default method basically checks to see what kind of object we're trying to serializeif it' contactwe convert it to dictionary manuallyotherwisewe let the parent class handle serialization (by assuming that it is basic typewhich json knows how to handlenotice that we pass an extra attribute to identify this object as contactsince there would be no way to tell upon loading it this is just conventionfor more generic serialization mechanismit might make more sense to store string type in the dictionaryor possibly even the full class nameincluding package and module remember that the format of the dictionary depends on the code at the receiving endthere has to be an agreement as to how the data is going to be specified we can use this class to encode contact by passing the class (not an instantiated objectto the dump or dumps functionc contact("john""smith"json dumps(ccls=contactencoder'{"is_contact"true"last""smith""full""john smith""first""john"}