saa*_*aan 1 postgresql psycopg2 jsonb
刚开始使用PostgreSQL 9.5,就遇到了jsonb列的第一个问题。我一直在努力寻找答案,但失败了。有人可以帮忙吗?
我在python中有一个包含以下json对象的json数组:
[{"name":"foo", "age":"18"}, {"name":"bar", "age":"18"}]
Run Code Online (Sandbox Code Playgroud)
我正在尝试将此插入到jsonb列中,如下所示:
COPY person(person_jsonb) FROM '/path/to/my/json/file.json';
Run Code Online (Sandbox Code Playgroud)
但是只插入了1行。我希望将数组中的每个json对象都添加为新行,如下所示:
1. {"name":"foo", "age":"18"}
2. {"name":"bar", "age":"18"}
Run Code Online (Sandbox Code Playgroud)
还尝试了:
INSERT INTO person(person_jsonb)
VALUES (%s)
,(json.dumps(data['person'])
Run Code Online (Sandbox Code Playgroud)
仍然只插入一行。有人可以帮忙吗?
编辑:根据要求添加了python代码
import psycopg2, sys, json
con = None
orders_file_path = '/path/to/my/json/person.json'
try:
with open(orders_file_path) as data_file:
data = json.load(data_file)
con = psycopg2.connect(...)
cur = con.cursor()
person = data['person']
cur.execute("""
INSERT INTO orders(orders_jsonb)
VALUES (%s)
""", (json.dumps(person), ))
con.commit()
except psycopg2.DatabaseError, e:
if con:
con.rollback()
finally:
if con:
con.close()
Run Code Online (Sandbox Code Playgroud)
person.json文件:
{"person":[{"name":"foo", "age":"18"}, {"name":"bar", "age":"18"}]}
Run Code Online (Sandbox Code Playgroud)
假设最简单的模式:
CREATE TABLE test(data jsonb);
Run Code Online (Sandbox Code Playgroud)
您需要将PostgreSQL中的每一行分开插入,可以在Python端解析JSON并拆分上层数组,然后使用cursor.executemany已拆分的每个JSON数据执行INSERT:
import json
import psycopg2
con = psycopg2.connect('...')
cur = con.cursor()
data = json.loads('[{"name":"foo", "age":"18"}, {"name":"bar", "age":"18"}]')
with con.cursor() as cur:
cur.executemany('INSERT INTO test(data) VALUES(%s)', [(json.dumps(d),) for d in data])
con.commit()
con.close()
Run Code Online (Sandbox Code Playgroud)
另一个选择是使用以下命令将JSON处理json_array_elements推入PostgreSQL端:
import psycopg2
con = psycopg2.connect('...')
cur = con.cursor()
data = '[{"name":"foo", "age":"18"}, {"name":"bar", "age":"18"}]'
with con.cursor() as cur:
cur.execute('INSERT INTO test(data) SELECT * FROM json_array_elements(%s)', (data,))
con.commit()
con.close()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3022 次 |
| 最近记录: |