使用 Python 在 Postgresql 中存储 Json 个对象数组
Store Array of Json Objects In Postgresql Using Python
我目前正在尝试使用 psycopg2 将两个 json 对象列表存储到我的 postgresql 数据库中,但没有成功。
这是我正在尝试做的事情的片段...
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 对象数组?
谢谢。
您需要使用 json
库并调用 json.dumps(dict_here)
。 Json 不是 Postgres 支持的类型。您使用 json.dumps
将字典转换为 json 字符串,然后使用 json.loads
将其转换回字典。
你需要给儿子施展价值——
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 索引而不是允许提高查询性能。
从这里开始:
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
我目前正在尝试使用 psycopg2 将两个 json 对象列表存储到我的 postgresql 数据库中,但没有成功。
这是我正在尝试做的事情的片段...
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 对象数组?
谢谢。
您需要使用 json
库并调用 json.dumps(dict_here)
。 Json 不是 Postgres 支持的类型。您使用 json.dumps
将字典转换为 json 字符串,然后使用 json.loads
将其转换回字典。
你需要给儿子施展价值——
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 索引而不是允许提高查询性能。
从这里开始:
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