I'm using SQLAlchemy extension with Flask. While serializing my models (which are also used for database operations) using jsonpickle, I want some specific attributes to be ignored. Is there a way that allows me to set those rules?
SQLAlchemy adds an attribute named _sa_instance_state to the object. In a word, I do not want this field to be in the JSON output.
You cannot tell the default class pickler to ignore something, no.
jsonpickledoes support thepicklemodule__getstate__and__setstate__methods. If your classes implement those two methods, whatever is returned is then used byjsonpickleto represent the state instead. Both methods do need to be implemented.If
__getstate__is not implemented,jsonpickleuses the__dict__attribute instead, so your own version merely needs to use that same dictionary, remove the_sa_instance_statekey and you are done:Whatever
__getstate__returns will be processed further, recursively, there is no need to worry about handling subobjects there.If adding
__getstate__and__setstate__is not an option, you can also register a custom serialization handler for your class; the disadvantage is that while__getstate__can get away with just returning a dictionary, a custom handler will need to return a fully flattened value.