SQLAlchemy JSON as blob/text

后端 未结 8 1868
猫巷女王i
猫巷女王i 2020-12-02 13:42

I\'m storing JSON down as blob/text in a column using MySQL. Is there a simple way to convert this into a dict using python/SQLAlchemy?

相关标签:
8条回答
  • 2020-12-02 14:36

    As an update to the previous responses, which we've used with success so far. As of MySQL 5.7 and SQLAlchemy 1.1 you can use the native MySQL JSON data type, which gives you better performance and a whole range of operators for free.

    It lets you to create virtual secondary indexes on JSON elements too.

    But of course you will lock yourself into running your app on MySQL only when moving the logic into the database itself.

    0 讨论(0)
  • 2020-12-02 14:40

    I think the JSON example from the SQLAlchemy docs is also worth mentioning:

    https://docs.sqlalchemy.org/en/13/core/custom_types.html#marshal-json-strings

    However, I think it can be improved to be less strict regarding NULL and empty strings:

    class JSONEncodedDict(TypeDecorator):
        impl = VARCHAR
    
        def process_bind_param(self, value, dialect):
            if value is None:
                return None
            return json.dumps(value, use_decimal=True)
    
        def process_result_value(self, value, dialect):
            if not value:
                return None
            return json.loads(value, use_decimal=True)
    
    0 讨论(0)
提交回复
热议问题