標籤:
SQLAlchemy轉換成json格式
SQLAlchemy查詢出來object轉換成json格式,如果資料模型中沒有使用外鍵的話。那麼可以直接調用object中的dict方法即可將object轉換成dict格式,之後json.dumps即可。
如果資料模型中使用了外鍵,在調用dict方法後,會有個一個”_sa_instance_state”的key,其value則是一個object,對於外鍵有很多個可配置對參數:
backref:在一對多或多對一之間建立雙向關係lazy:預設值是True,說明關聯對象只有到真正訪問的時候才會去查詢資料庫,比如有parent對象,只有知道訪問parent.children的時候才做關聯查詢,這就是上面所說的在調用了dict後,對於的外部索引鍵關聯會產生一個關聯表的查詢object。
對於存在外鍵的查詢格式化成json的需求,可以通過如下代碼來實現:
import json class ComplexEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, datetime.datetime): return obj.strftime(‘%Y-%m-%d %H:%M:%S‘) elif isinstance(obj, datetime.date): return obj.strftime(‘%Y-%m-%d‘) else: return json.JSONEncoder.default(self, obj) def obj_to_json(obj_list): out = [q.__dict__ for q in obj_list] for objs, instance in zip(out, obj_list): for obj in objs.values(): if callable(obj): for name in obj.mapper.relationships.keys(): tmp = getattr(instance, name).__dict__ if "_sa_instance_state" in tmp.keys(): tmp.pop("_sa_instance_state") tmp.pop("id") objs.update(tmp) objs.pop(name) if "_sa_instance_state" in objs.keys(): objs.pop("_sa_instance_state") return out def query_result_json(query_result): """ Convert query result to json format """ if isinstance(query_result, list): result = obj_to_json(query_result) elif getattr(query_result, ‘__dict__‘, ‘‘): result = obj_to_json([query_result]) else: result = {‘result‘: query_result} return json.dumps(result, cls=ComplexEncoder)import json class ComplexEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, datetime.datetime): return obj.strftime(‘%Y-%m-%d %H:%M:%S‘) elif isinstance(obj, datetime.date): return obj.strftime(‘%Y-%m-%d‘) else: return json.JSONEncoder.default(self, obj) def obj_to_json(obj_list): out = [q.__dict__ for q in obj_list] for objs, instance in zip(out, obj_list): for obj in objs.values(): if callable(obj): for name in obj.mapper.relationships.keys(): tmp = getattr(instance, name).__dict__ if "_sa_instance_state" in tmp.keys(): tmp.pop("_sa_instance_state") tmp.pop("id") objs.update(tmp) objs.pop(name) if "_sa_instance_state" in objs.keys(): objs.pop("_sa_instance_state") return out def query_result_json(query_result): """ Convert query result to json format """ if isinstance(query_result, list): result = obj_to_json(query_result) elif getattr(query_result, ‘__dict__‘, ‘‘): result = obj_to_json([query_result]) else: result = {‘result‘: query_result} return json.dumps(result, cls=ComplexEncoder)
python sqlalchemy JSON