python - 如何将 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 格式时遇到了很多问题。请建议。
解决方案
您的数据基本上是一个元组列表。
就像第一个元组一样
('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)
推荐阅读
- c++ - 仅具有布尔文字值的概念是否格式错误,不需要诊断?
- kubernetes - 什么是 Istio 子集
- azure - 是否从 azure 服务总线的 go 客户端库处理重试?
- selenium - 在 selenium 中添加 firefox 驱动程序时出现 SessionNotCreatedException
- python - Pyspark:如何使用 UDF 过滤表?
- c++ - UE4:仅更改属性的自定义 NetReplicate
- node.js - GCP Cloud Run 对使用 http2 的长时间运行请求产生间歇性 503 错误
- reactjs - 当状态改变时动态改变 Formik 中的值
- ruby - Ruby:无法访问全局变量,不是以 $ 开头
- python - 如何迭代抓取 url 列表中的所有表格?