【发布时间】: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变为relativeHumidity和wind变为windSpeed - 将
log和lat字段合并为单个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