Convert Python list of dicts into Postgresql array of json

佐手、 提交于 2019-12-06 06:10:51
piro

This is not a psycopg error: it is a PostgreSQL error psycopg is just relying.

The error seems suggesting there is no implicit text[]->jsonb[] cast so you need to add a manual one:

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

Use 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 will return a set of jsonb which will be turned into an array of jsonb by array_agg

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!