在SQLAlchemy中区分RowProxy的json列?

问题描述 投票:0回答:1

例如,当我执行以下代码时,结果数据类型为str

result = engine.execute('''
  SELECT CAST('{"foo": "bar"}' as JSON) as `json`
''')
row = result.fetchone()
json = row[0]
type(json)

具有str类型的json列值并不是元编程友好的。

Question

有没有办法从result(或ResultProxy的一个实例)获取每列类型的信息?

env

  • MySQL:8.0.11
  • SQLAlchemy:1.3.0
  • pymysql:0.9.3
python sqlalchemy pymysql
1个回答
2
投票

您至少可以通过明确的telling SQLAlchemy that the result is JSON实现它:

from sqlalchemy.types import JSON

stmt = text('''SELECT CAST('{"foo": "bar"}' as JSON) as `json`''')
stmt = stmt.columns(json=JSON)

row = engine.execute(stmt).fetchone()
type(row.json)
© www.soinside.com 2019 - 2024. All rights reserved.