SQLAlchemy JSON为blob / text [英] SQLAlchemy JSON as blob/text
本文介绍了SQLAlchemy JSON为blob / text的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用MySQL存储JSON作为blob /文本在列中。使用python / SQLAlchemy将一个简单的方法转换为一个字典。
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?
推荐答案
http://www.sqlalchemy.org/docs/core/types.html#custom-typesrel =nofollow noreferrer>使用SQLAlchemy
You can very easily create your own type with SQLAlchemy
对于SQLAlchemy版本> = 0.7,请查看 Yogesh的回答
For SQLAlchemy versions >= 0.7, check out Yogesh's answer below
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)时使用:
This can be used when you are defining your tables (example uses 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。
You can also use a different json serialiser to jsonpickle.
这篇关于SQLAlchemy JSON为blob / text的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文