gpt4 book ai didi

python - 将 SQLAlchemy 输出转储到 JSON

转载 作者:太空宇宙 更新时间:2023-11-04 09:07:20 28 4
gpt4 key购买 nike

我写了一个小的 python 脚本,它使用 SQLAlchemy 读取数据库的所有记录。这是部分代码

Base=declarative_base()
Session = sessionmaker(bind=engine)
cess=Session()

class Test(Base):
__tablename__ = 'test'
my_id = Column(Integer, primary_key=True)
name = Column(String)
def __init__(self, id, name):
self.my_id = id
self.name = name
def __repr__(self):
return "<User('%d','%s')>" % (self.id, self.name)



query= cess.query(Test.my_id, Test.name).order_by(Test.my_id).all()

现在我要将查询对象转换为 json 字符串。我怎样才能做到这一点 ?使用 json.dumps(query) 抛出异常?

亲切的问候

最佳答案

json.dumps将根据其 conversion table 转换对象.

因为您有 Test 类型的行,所以不能直接序列化这些行。可能最快的方法是将每个返回的行转换为 Python dict,然后将其传递给 json.dumps

This answer描述了如何将表格行转换为字典。

或者,也许是 _asdict()来自 row 对象的方法可以直接使用。

query = cess.query(Test.my_id, Test.name).order_by(Test.my_id).all()

json.dumps([ row._asdict() for row in query ])

另一种方法可能是直接在每一行上访问 __dict__ 属性,尽管您应该检查输出以确保 row.__dict__ 中没有内部状态变量.

query = cess.query(Test.my_id, Test.name).order_by(Test.my_id).all()

json.dumps([ row.__dict__ for row in query ])

关于python - 将 SQLAlchemy 输出转储到 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19110164/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com