I wanted to save/load JSON to SQLAlchemy transparently, the same way you can with PickleType. Also I wanted to know how to do value conversion generally in SQLAlchemy. So here is a custom SQLAlchemy type: JSONType, it uses simplejson to do the actual JSON parsing/serialization.
import simplejson
from sqlalechmy.types import Text, MutableType, TypeDecorator
class JSONType(MutableType, TypeDecorator):
impl = Text
def __init__(self):
super(JSONType, self).__init__()
def process_bind_param(self, value, dialect):
return simplejson.dumps(value)
def process_result_value(self, value, dialiect):
return simplejson.loads(value)
def copy_value(self, value):
return simplejson.loads(simplejson.dumps(value))
No comments:
Post a Comment