Yuki Inoue
Yuki Inoue

Reputation: 3787

distinguishing json column of RowProxy in SQLAlchemy?

For example, when I execute following code, resulting data type is str:

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

An json column value having type of str is not so much meta-programming friendly.

Question

Is there any way to fetch information from the result (or, an instance of ResultProxy) what each column's type was?

env

Upvotes: 0

Views: 73

Answers (1)

Ilja Everilä
Ilja Everilä

Reputation: 52957

You can at least achieve it by explicitly 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)

Upvotes: 2

Related Questions