我想用 pandas 生成一个数据框read_sql https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_sql.html来自我使用 PostgreSQL 进行的 sqlalchemy 查询jsonb https://www.postgresql.org/docs/9.5/static/functions-json.html属性到列。
实际上这会给我我的答案:
query = session.query(
cls.id,
cls._my_jsonb_column
).all()
pd.DataFrame.from_dict([dict(id=id_, **i) for id_,i in query])
但我更愿意使用 PostgreSQL 而不是在应用程序中解压 jsonb。
我的尝试给出了
query = session.query(
cls.id,
func.jsonb_to_record(cls._my_jsonb_column)
)
pd.read_sql(query.statement, query.session.bind)
(psycopg2.NotSupportedError) 函数返回在无法接受类型记录的上下文中调用的记录
json_to_record
(and jsonb_to_recordset
) 返回记录,就好像它是 a 的结果SELECT
询问。在 sqlalchemy 上下文中,它提供了一个可以像表一样使用的可选择项。
所以你应该考虑的结果func.jsonb_to_record(cls._my_jsonb_column)
作为一种表格,您可以将其加入到原始表格中。
也就是说,您的查询应该如下所示:
jsonb_data = func.jsonb_to_record(cls._my_jsonb_column)
query = session.query(
select(
[cls.id, <other columns>]
).select_from(
cls.join(jsonb_data, <on_clause>)
)
)
您甚至可以使用以下方式展平 JSON 数据JSON处理函数 https://www.postgresql.org/docs/current/functions-json.html但如果不知道 JSON 数据的结构,就不可能更精确。
另外,我最近发布了一个包,可以轻松地从 json 数据的描述中展平 JSONB 字段,我很高兴收到一些反馈:pg_jsonb_flattener https://pypi.org/project/pg-jsonb-flattener/
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)