Python存储列表作为postgres数据库中的数组

问题描述 投票:0回答:1

我正在尝试将我的json文件中的数据存储在postgres数据库中。我在存储数组时遇到了问题。当我解码我的json文件时,我的一个字段看起来像这样:

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

当我试图将其插入我的数据库列(使用text []格式)时,我收到错误。唯一可接受的格式是:

{{Global,0},{Poland,150}}

我不知道该怎么做。

我试过for循环,但它给了我0然后全局值,但我首先需要全局然后0。它应该适用于所有这样的数组,不仅仅是键'wartosc'和'tytul'

我桌子的架构:enter image description here

我正在尝试将我的数据存储在similar_web中

python postgresql
1个回答
0
投票

您需要传递一个字符串列表作为查询参数,以便PostgreSQL Python driver would automatically convert it to the text[] 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)
© www.soinside.com 2019 - 2024. All rights reserved.