【问题标题】:Store Array of Json Objects In Postgresql Using Python使用 Python 在 Postgresql 中存储 Json 对象数组
【发布时间】:2017-06-22 06:11:51
【问题描述】:

我目前正在尝试使用 psycopg2 将两个 json 对象列表存储到我的 postgresql 数据库中,但没有成功。

这是我正在尝试做的事情的 sn-p...

SQL_INSERT_QUERY = """INSERT INTO table (
                              x,
                              json_list_one,
                              json_list_two
                            ) VALUES (%s, %s, %s)"""

def insert_stuff(id, json_list_one, json_list_two):
values = (
    id,
    map(psycopg2.extras.Json, json_list_one),
    map(psycopg2.extras.Json, json_list_two)
)
conn = get_connection_pool().getconn()
try:
    cur = conn.cursor()
    cur.execute(SQL_INSERT_QUERY, values)
    conn.commit()
    cur.close()
finally:
    get_connection_pool().putconn(conn)

当前的实现导致了这个错误...

An exception of type ProgrammingError occured. Arguments:
('column "json_list_one" is of type json[] but expression is of type text[]\nLINE 5: ...) VALUES (\'9527d790-31dc-46fa-b683-c6fc9807c2a4\', ARRAY[\'{"h...\n                                                             ^\nHINT:  You will need to rewrite or cast the expression.\n',)

有人知道我应该如何在 PostgreSQL 中插入一个 json 对象数组吗?

谢谢。

【问题讨论】:

标签: python arrays json postgresql psycopg2


【解决方案1】:

你需要给儿子施放价值——

SQL_INSERT_QUERY = """INSERT INTO table (
                              x,
                              json_list_one,
                              json_list_two
                            ) VALUES (%s, %s::json[], %s::json[])"""

如果您使用 PostgreSQL 9.5 或更高版本,您需要查询 json 字段,最好将 json 更改为 jsonb。 Jsonb 允许创建 GIN 索引而不是提高查询的性能。

【讨论】:

  • 这将返回 DETAIL: Array value must start with "{" or dimension information 。有什么问题?
  • 默认情况下,postgres 将未知数据转换为文本。正如您在错误 'column "json_list_one" is of type json[] but expression is of type text[] 中看到的,而不是错误类型字段中的错误 - text[] 而不是 json[]
【解决方案2】:

从这里:https://stackoverflow.com/a/45150668/3598837

from psycopg2.extras import Json

cur = conn.cursor()

cur.execute('INSERT into some_table (uuid, dict) values (%s, %s)',
    ['testName', Json([{'name':'test','number':'444-444-4444'}, {'name':'test','number':'555-555-5555'}])])
#the rest of it

【讨论】:

    【解决方案3】:

    您需要使用json 库并调用json.dumps(dict_here)。 Json 不是 Postgres 中支持的类型。您使用json.dumps 将字典转为json 字符串,并使用json.loads 将其转回字典。

    【讨论】:

    • 实际上 PosgreSQL 确实支持 Json 类型(从 9.3 开始?)。我已经将 Json(不是作为数组)存储在其他表中。
    猜你喜欢
    • 2023-01-17
    • 1970-01-01
    • 1970-01-01
    • 2021-10-25
    • 2015-10-28
    • 2021-01-29
    • 2018-04-05
    • 1970-01-01
    • 2016-05-21
    相关资源
    最近更新 更多