[英]How to merge JSON arrays into a single array
我的 PostgreSQL 數據庫。 我需要通過 sqlalchemy 擺脫 JSON 嵌套。
組列組中的數據
團體 |
---|
[{“id”:5,“名稱”:“imba”}] |
[{"id": 1, "name": "group1"}, {"id": 3, "name": "group3"}] |
如何在 SQLAlchemy 中創建查詢?
預期結果
[{"id": 5, "name": "imba"}, {"id": 1, "name": "group1"}, {"id": 3, "name": "group3"}]
像這樣在 Postgresql 中給定一個表
test# table t73051318;
id_ │ groups
═════╪════════════════════════════════════════════════════════════
1 │ [{"id": 5, "name": "imba"}]
2 │ [{"id": 1, "name": "group1"}, {"id": 3, "name": "group3"}]
(2 rows)
我們可以通過對groups
列上調用jsonb_array_elements
的結果調用json_agg
函數來合並 JSONB 值。
test# select json_agg(row) as aggregated
from (select jsonb_array_elements(groups) as row
from t73051318
) q;
aggregated
═══════════════════════════════════════════════════════════════════════════════════════
[{"id": 5, "name": "imba"}, {"id": 1, "name": "group1"}, {"id": 3, "name": "group3"}]
(1 row)
在 SQLAlchemy 核心中,代碼如下所示:
import sqlalchemy as sa
# Create a subquery for the jsonb_array_elements call.
subq = sa.select(
sa.func.jsonb_array_elements(tbl.c.groups).label('row')
).subquery()
# Aggregate the subquery result.
stmt = sa.select(sa.func.json_agg(subq.c.row).label('aggregated'))
with engine.connect() as conn:
res = conn.execute(stmt)
print(next(res).aggregated)
在 Flask-SQLAlchemy 中,代碼是
# Create a subquery for the jsonb_array_elements call.
subq = db.session.query(
db.func.jsonb_array_elements(MyModel.groups).label('row')
).subquery()
# Aggregate the subquery result.
stmt = db.session.query(db.func.json_agg(subq.c.row).label('aggregated'))
result = stmt.first()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.