在Postgres数据库中将Python存储列表为数组

2024-09-01 18:39:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图将json文件中的数据存储到postgres数据库中。我在存储数组时遇到问题。当我解码json文件时,我的一个字段如下所示:

[{u'wartosc': u'0', u'tytul': u'Global'}, {u'wartosc': u'150', u'tytul': u'Poland'}]

当我试图在我的数据库列(文本[]格式)中插入它时,我遇到了错误。唯一可接受的格式是:

^{pr2}$

我不知道怎么做。在

我尝试过for循环,但它给我的值是0,然后是全局的,但我需要先全局,然后是0。它应该适用于所有像这样的阵列,而不仅仅是密钥'wartosc'和'tytul'

我的表的架构: enter image description here

我试着把我的数据存储在类似的网络上


Tags: 文件数据文本数据库json格式错误postgres
1条回答
网友
1楼 · 发布于 2024-09-01 18:39:56

您需要将字符串列表作为查询参数传递给以便PostgreSQL Python driver would automatically convert it to the ^{} array type

input_data = [{u'wartosc': u'0', u'tytul': u'Global'}, {u'wartosc': u'150', u'tytul': u'Poland'}]

data = [[item['tytul'], item['wartosc']] for item in input_data]

cursor.executemany("""
    INSERT INTO 
        TABLE_NAME
        (similar_web)
    VALUES
        (%s)
""", data)

相关问题 更多 >