首页 > 解决方案 > 如何将 SQLAlchemy 数据转换为 JSON 格式?

问题描述

我正在研究 SQLAlchemy,想从数据库中获取数据并将其转换为 JSON 格式。

我有以下代码:

db_string = "postgres://user:pwd@10.**.**.***:####/demo_db"
Base = declarative_base()
db = create_engine(db_string)  

record = db.execute("SELECT name, columndata, gridname, ownerid, issystem, ispublic, isactive FROM col.layout WHERE (ispublic=1 AND isactive=1) OR                                            (isactive=1 AND ispublic=1 AND ownerid=ownerid);")

for row in record:
    result.append(row)

print(result)

数据以这种格式出现:

[('layout-1', {'theme': 'blue', 'sorting': 'price_down', 'filtering': ['Sub Strategye', 'PM Strategy']}, 'RealTimeGrid', 1, 0, 1, 1), ('layout-2', {'theme': 'orange', 'sorting': 'price_up', 'filtering': ['FX Rate', 'Start Price']}, 'RealBalancing Grid', 2, 0, 1, 1), ('layout-3', {'theme': 'red', 'sorting': 'mv_price', 'filtering': ['Sub Strategye', 'PM Strategy']}, 'RT', 3, 0, 1, 1)]

但是我在将上述结果转换为 JSON 格式时遇到了很多问题。请建议。

标签: pythonsqlalchemy

解决方案


您的数据基本上是一个元组列表。

就像第一个元组一样

('layout-3',
 {'filtering': ['Sub Strategye', 'PM Strategy'],
  'sorting': 'mv_price',
  'theme': 'red'},
 'RT',
 3,
 0,
 1,
 1)

如果要将整个数据原样转换为 json,可以使用json模块dumps功能

import json
jsn_data = json.dumps(data)

您的元组列表已转换为 json

[["layout-1", {"theme": "blue", "sorting": "price_down", "filtering": ["Sub Strategye", "PM Strategy"]}, "RealTimeGrid", 1, 0, 1, 1], ["layout-2", {"theme": "orange", "sorting": "price_up", "filtering": ["FX Rate", "Start Price"]}, "RealBalancing Grid", 2, 0, 1, 1], ["layout-3", {"theme": "red", "sorting": "mv_price", "filtering": ["Sub Strategye", "PM Strategy"]}, "RT", 3, 0, 1, 1]]

但是如果您需要json格式作为键值对,首先需要将结果转换为python字典然后使用json.dumps(dictionary_Var)


推荐阅读