使用 psycopg2 将包含 JSON 数组字段的元组列表插入到 Postgres 数据库中

Using psycopg2 to insert list of tuples which includes a JSON array field into Postgres database

我正在尝试将行插入到具有三列的数据库中:出版物、publication_year 和作者。字段 authors 的类型为 JSON []。目前,我有以下代码:

query = "INSERT INTO " + store_table_name + "( " + ",".join(tuple(key_types.keys())) + ") VALUES %s"
try:
    # connect to the database
    conn, cur = pg_connect(DB_OSP, db_host, db_user, db_password)
    conn.set_isolation_level(psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT)

    logger.info('Adding %s rows to %s' % (len(data), store_table_name))

    execute_values(cur, query, data)

    cur.close()
    conn.commit()
# exception handling to follow

数据是一个元组列表,其中每个条目都是(出版物,publication_year,作者)。因此,例如,条目可能如下所示:

('Sample Book', 2019, ['{"Author1_fname": "Billy", "Author1_lname": "Bob"}', '{"Author2_fname": "King", "Author2_lname": "Kong"}'])

最初,代码不起作用,因为存在类型不匹配(它尝试将作者作为文本数组而不是 JSON 数组插入)。我尝试将数组更改为字符串类型,但这也不起作用。我不太确定如何使用 execute_values 显式添加“:::json[]”强制转换。有没有人有这方面的经验?

尝试使用 psycopg2.extras 中的 Json,将数据格式化为:

(
  "Sample Book",
  2019, 
  Json([{"Author1_fname": "Billy", "Author1_lname": "Bob"}, {"Author2_fname": "King", "Author2_lname": "Kong"}])
)