Python 从psycopg2在Postgres中插入dict as json数组列表

Python 从psycopg2在Postgres中插入dict as json数组列表,python,postgresql,psycopg2,Python,Postgresql,Psycopg2,我有这张桌子在博士后 CREATE TABLE target ( a json ) 我想使用 import psycopg2 import psycopg2.extras as extras # a is list of list of dicts a = [[{'a':1,'b':2}, {'d':3,'e':2}], [{'a':3,'b':1}, {'e':2,'f':6}]] # convert a to list of tuples containing ex

我有这张桌子在博士后

CREATE TABLE target (
    a json
)
我想使用

import psycopg2
import psycopg2.extras as extras

# a is list of list of dicts
a = [[{'a':1,'b':2}, {'d':3,'e':2}],
      [{'a':3,'b':1}, {'e':2,'f':6}]]

# convert a to list of tuples containing extras.Json objects
a = [(extras.Json(x),) for x in a]

# insert a to the database
query = ('WITH ins (a) AS '
         '(VALUES %s) '
         'INSERT INTO target (a) '
         'SELECT ins.a '
         'FROM ins;')

cursor = conn.cursor()

extras.execute_values(cursor, query, a)

但是我得到了一个错误:
列“a”的类型是json,而表达式的类型是text

为了使问题更清楚,这个例子被简化了(这就是为什么这个示例使用
WITH ins
语句,因为我需要将一个表连接到它。我本以为这应该可以工作,但由于某种原因它不能工作。我怀疑的是,问题是我首先将它加载到ins中,可能出于某种原因,默认情况下它将作为文本而不是json加载到ins中

如何解决这个问题?

类似这样的问题:

CREATE TABLE target (
    a json
)

query = "INSERT INTO target VALUES %s"  

b = [[extras.Json(row)] for row in a] 
cur = con.cursor()
extras.execute_values(cur, query, b)
con.commit()

select * from target;
                  a                   
--------------------------------------
 [{"a": 1, "b": 2}, {"d": 3, "e": 2}]
 [{"a": 3, "b": 1}, {"e": 2, "f": 6}]

直接从输入值简化为
INSERT
。我创建了一个列表作为
execute\u值
可以采用一系列序列或一系列字典(如果使用命名参数)

更新:

query = ('WITH ins (a) AS '
         '(VALUES %s) '
         'INSERT INTO target (a) '
         'SELECT ins.a::json '
         'FROM ins;')



非常感谢您的回答。不幸的是,
WITH ins
语句是必需的,因为我需要将一个表加入其中。可能我过于简单化了。是否需要调整您的方法以使用ins…@sev处理
,请参阅更新。我假设此解决方案将json作为文本加载到ins中,然后选择时将其从文本转换为json?是的,就是这样。