将DICT的Python列表转换为json的Postgresql数组

将DICT的Python列表转换为json的Postgresql数组,python,json,postgresql,psycopg2,Python,Json,Postgresql,Psycopg2,我试图将jsonb元素的Python(2.7)列表插入到一个数据类型为jsonb[]的Postgresql(9.4)表中 下面是一些代码: import json anArray = [{"name":"Joe","age":51,"yob":1964,"gender":"male"},{"name":"George","age":41,"dob":1974,"gender":"male"},{"name":"Nick","age":31,"dob":1984,"gender":"male"}]

我试图将jsonb元素的Python(2.7)列表插入到一个数据类型为jsonb[]的Postgresql(9.4)表中

下面是一些代码:

import json
anArray = [{"name":"Joe","age":51,"yob":1964,"gender":"male"},{"name":"George","age":41,"dob":1974,"gender":"male"},{"name":"Nick","age":31,"dob":1984,"gender":"male"}]
myArray = []
#here's what I have so far: 
for e in anArray:
    myArray.append(json.dumps(e))
#this gives me
myArray = ['{"name":"Joe","age":51,"yob":1964,"gender":"male"}','{"name":"George","age":41,"dob":1974,"gender":"male"}','{"name":"Nick","age":31,"dob":1984,"gender":"male"}']
#insert commands
insert_sql = "INSERT INTO my_table (data) VALUES (%s);"
insert_data = (myArray, )
cursor.execute(insert_sql, insert_data)
现在,当我尝试插入myArray时,psycopg2给了我一个错误

psycopg2.ProgrammingError: column "data" is of type jsonb[] but expression is of type text[]
我不太确定将这些数据插入表中的正确语法是什么。如有任何帮助/建议,将不胜感激

解决方案 多亏了皮罗,这是一个快速的解决方案

insert_sql = "INSERT INTO my_table (columns) VALUES (%s::jsonb[]);"
insert_data = (myArray, )
cursor.execute(insert_sql, insert_data)

这不是psycopg错误:这是psycopg所依赖的PostgreSQL错误

错误似乎表明没有隐式文本[]->jsonb[]cast,因此需要添加手动文本:

INSERT INTO my_table (columns) VALUES (%s::jsonb[]);
使用


jsonb\u array\u elements
将返回一组
jsonb
,它将由
array\u agg

转换为
jsonb
的数组,然后。。。这很有魅力。非常感谢@piro!我尝试过这样做,但它创建了一个无法插入的空json:
'{}'
详细信息:数组值必须以“{”或维度信息开头。
这是最好的解决方案。
from psycopg2.extras import Json

data = [
    {"name":"Joe","age":51,"yob":1964,"gender":"male"},
    {"name":"George","age":41,"dob":1974,"gender":"male"},
    {"name":"Nick","age":31,"dob":1984,"gender":"male"}
]

query = '''
    insert into t (j)
    select array_agg(j)
    from jsonb_array_elements(%s) s(j)
'''

cursor.execute(query, (Json(data),))