【发布时间】:2020-02-25 20:32:56
【问题描述】:
我已经有代表 json-reply 模型的表的数据库
我正在使用 Base = automap_base() 来创建这样的类
import simplejson as json
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import Session
from sqlalchemy import create_engine
from sqlalchemy.orm.attributes import QueryableAttribute
Base = automap_base()
# engine, suppose it has two tables 'user' and 'address' set up
engine = create_engine("mysql+pymysql://test:test@localhost/test")
# reflect the tables
Base.prepare(engine, reflect=True)
session = Session(engine)
Person = Base.classes.person
persons = session.query(Person).all()
for person in persons:
print (person.name)
s = json.dumps([dict(r) for r in persons.values()])
我有这个错误:
Traceback (most recent call last):
File "c:/Users/rusagm/pythonProjects/sqlalchemytest/send.py", line 24, in <module>
s = json.dumps([dict(r) for r in persons])
File "c:/Users/rusagm/pythonProjects/sqlalchemytest/send.py", line 24, in <listcomp>
s = json.dumps([dict(r) for r in persons])
TypeError: 'person' object is not iterable
我想从我的 sqlalchemy 自动映射查询创建 json。我该怎么办?
【问题讨论】:
-
将查询响应加载到
pandas数据帧中,然后使用df.to_json保存到 json。
标签: python json sqlalchemy