小编saa*_*aan的帖子

在PostgreSQL 9.5中将包含json对象的数组作为行插入

刚开始使用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)

postgresql psycopg2 jsonb

1
推荐指数
1
解决办法
3022
查看次数

标签 统计

jsonb ×1

postgresql ×1

psycopg2 ×1