【问题标题】:Python: Retrieving PostgreSQL query results as formatted JSON valuesPython:将 PostgreSQL 查询结果检索为格式化的 JSON 值
【发布时间】:2019-09-08 06:56:41
【问题描述】:

我正在使用一个包含多个表的 postgres 数据库。目标是从获得的查询结果中检索格式化的 JSON。我创建了这个从表(测试用例)中获取数据集的python脚本,以便操作查询结果:

import psycopg2
import json
from time import sleep
from config import config

def main():
    conn = None
    try:
        params = config()
        conn = psycopg2.connect(**params)
        cur = conn.cursor()
        cur.execute("select * from location")
        row = cur.fetchone()

        while row is not None:
            print(row)
            #do field rename, merge(log, lat) and obtained JSON here
            sleep(0.3)
            row = cur.fetchone()

        cur.close()
    except (Exception, psycopg2.DatabaseError) as error:
        print(error)
    finally:
        if conn is not None:
            conn.close()

if __name__ == '__main__':
    main()

为了让我的问题更清楚,我在这里制作了一个简化的场景,用 3 个表格表示手头的任务,如下所示。

environment
╔════════╦═══════════╦══════╦══════╗
║ env_id ║ placem_id ║ humd ║ wind ║
╠════════╬═══════════╬══════╬══════╣
║     104║        4  ║   48 ║  119 ║
║     68 ║        9  ║   39 ║  141 ║
╚════════╩═══════════╩══════╩══════╝

placement
╔═══════════╦════════╦═══════════════╦══════════════════════════╗
║ placem_id ║ loc_id ║  description  ║           date           ║
╠═══════════╬════════╬═══════════════╬══════════════════════════╣
║         4 ║     64 ║ description_1 ║ 2019-03-12T20:40:35.967Z ║
║         7 ║      5 ║ description_2 ║ 2019-03-12T20:56:51.319Z ║
╚═══════════╩════════╩═══════════════╩══════════════════════════╝

location
╔════════╦═══════════╦═══════════╦════════════════════╗
║ loc_id ║    log    ║    lat    ║      address       ║
╠════════╬═══════════╬═══════════╬════════════════════╣
║     64 ║ 13.3986   ║ 52.5547   ║ Bosebrucke Einkauf ║
║     71 ║ 21.150122 ║ -6.607044 ║ Charlotte Court    ║
╚════════╩═══════════╩═══════════╩════════════════════╝

这是我想要实现的目标:

  • 从数据库中检索记录
  • 在 JSON 名称/值中根据需要重命名某些字段(例如,humd 变为 relativeHumiditywind 变为 windSpeed
  • loglat 字段合并为单个JSON 值,例如coordinate[log,lat]

这样返回的 JSON 格式为:

{
    "relativeHumidity": 48,
    "windSpeed": 119,
    "address": "Bosebrucke Einkauf",
    "location": {
        "coordinates": [13.3986, 52.5547]
    }
}

虽然这个问题可能看起来是重复的,但我尝试了许多针对类似问题的建议,例如here,但这些都没有真正起作用。

有人可以提供指导吗?

【问题讨论】:

    标签: python sql json python-3.x postgresql


    【解决方案1】:

    我觉得functions-json应该比较容易做到:

    select
        json_agg(to_json(d))
    from (
        select
            e.humd as "relativeHumidity",
            e.wind as "windSpeed",
            l.address,
            json_build_object(
                'coordinates',
                json_build_array(l.log, l.lat)
            ) as location
        from environment as e
            inner join placement as p on
                p.placem_id = e.placem_id
            inner join location as l on
                l.loc_id = p.loc_id
    ) as d
    

    db<>fiddle demo

    【讨论】:

    • 非常感谢这篇简短而准确的文章。它确实有效。我第一次遇到这个 db fiddle。
    • 假设我希望每条记录作为单个 JSON 对象返回,而不是作为单个 JSON 的整个查询结果返回(假设我希望每 1 秒记录一次)。请问如何修改上述查询。工作但不成功(编写python脚本)。
    • 删除json_agg - dbfiddle.uk/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-09
    • 1970-01-01
    • 2017-10-03
    相关资源
    最近更新 更多