[英]Json import to postgresql with python
我正在尝试使用以下代码将多个 json 文件导入我的 postgres 数据库。
import json
import psycopg2
con = psycopg2.connect(database="kw_du", user="postgres", password="f67dd8hzFE5",host="localhost")
cur = con.cursor()
with open(r"C:\Users\diego\OneDrive\Desktop\Workplace\220906\nu_2022_09_01.json", 'r') as data_file:
data = json.load(data_file)
with con.cursor() as cur:
cur.executemany('INSERT INTO test_nu(vp_ip, system_activ, vpm_activ) VALUES(%s)', [(json.dumps(d),) for d in data])
con.commit()
con.close()
json文件结构如下:
[{"vp_id":1,"system_activ":1,"vpm_activ":1},{"vp_id":2,"system_activ":2,"vpm_activ":2}]
执行代码时,我收到以下错误消息:
第 13 行,在 cur.executemany('INSERT INTO test_nu (vp_id, system_aktiv) VALUES(%s)', [(json.dumps(d),) for d in data]) psycopg2.errors.SyntaxError: ERROR: INSERT has目标列多于表达式 LINE 1: INSERT INTO test_nu (vp_id, system_aktiv) VALUES('{"vp_id": ...
我已经看到, ERROR: INSERT has more target columns than expressions can have varios原因,我无法解决这个问题。 ' 或 {} 可能有问题吗? 似乎 json 对象没有被解析VALUES('{"vp_id": ...感谢任何提示。
您可以使用以下方法保存到数据库的多次往返:
with expand as (
select (j->>'vp_id')::int as vp_ip,
(j->>'system_activ')::int as system_activ,
(j->>'vpm_activ')::int as vpm_activ
from jsonb_array_elements((%s)::jsonb) as el(j)
)
insert into test_nu (vp_id, system_activ, vpm_activ)
select vp_ip, system_activ, vpm_activ
from expand;
json.dumps(data)
传递给此查询。
您可以使用json_populate_recordset
。
请参阅下面的示例查询 -
insert into test_nu(vp_id, system_activ, vpm_activ) select * from json_populate_recordset(NULL::test_nu,'[{"vp_id": 1,"system_activ":"eewrw","vpm_activ":"qeqerqr"}]')
在这里拉小提琴。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.