将Python的dicts列表转换为json

时间:2015-07-26 20:59:15

标签: python json postgresql psycopg2

我试图将一个Python(2.7)jsonb元素列表插入到Postgresql(9.4)表中,其中包含一个数据类型:jsonb []。

以下是一些代码:

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[]

我不太确定将此数据插入表中的正确语法是什么。任何帮助/指针将不胜感激。

解决方案 感谢piro,这是一个快速的解决方案。

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

2 个答案:

答案 0 :(得分:5)

这不是psycopg错误:它是一个PostgreSQL错误psycopg只是依赖。

错误似乎表明没有隐式文本[] - > jsonb []强制转换,因此您需要添加一个手册:

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

答案 1 :(得分:3)

使用Psycopg JSON adaptation

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),))

jsonb_array_elements将返回一组jsonb,该jsonb将被array_agg

转换为{{1}}数组