我使用 MySQL 将 JSON 作为 blob/文本存储在列中。有没有一种简单的方法可以使用 python/SQLAlchemy 将其转换为字典?
最佳答案
您可以非常轻松地create your own type使用 SQLAlchemy
对于 SQLAlchemy 版本 >= 0.7,请查看 Yogesh's answer下面
import jsonpickle
import sqlalchemy.types as types
class JsonType(types.MutableType, types.TypeDecorator):
impl = types.Unicode
def process_bind_param(self, value, engine):
return unicode(jsonpickle.encode(value))
def process_result_value(self, value, engine):
if value:
return jsonpickle.decode(value)
else:
# default can also be a list
return {}
这可以在您定义表时使用(示例使用 elixir):
from elixir import *
class MyTable(Entity):
using_options(tablename='my_table')
foo = Field(String, primary_key=True)
content = Field(JsonType())
active = Field(Boolean, default=True)
您还可以使用不同的 json 序列化程序来 jsonpickle。
关于python - SQLAlchemy JSON 作为 blob/文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4038314/