如何在Postgres中使用json参数调用函数

时间:2018-09-25 21:22:46

标签: json postgresql psycopg2 jsonb

我必须将json对象传递给函数,但它不起作用:

import psycopg2
cur.execute(" SELECT mrp_sp_insert_jobdef( %s )",(json(_jobdef),) )

TypeError: 'module' object is not callable

或者:

cur.execute(" SELECT mrp_sp_insert_jobdef( % )",(json.dumps(_jobdef),) )

ValueError: unsupported format character ' ' (0x20) at index 31

1 个答案:

答案 0 :(得分:1)

您可以使用包装器psycopg2.extras.Json(adapted, dumps=None),例如:

import psycopg2
from psycopg2.extras import Json

conn = psycopg2.connect("dbname=test user=postgres password=password")
cur = conn.cursor()

_jobdef = {'id': 1, 'name': 'product', 'amount': 230}
cur.execute("SELECT mrp_sp_insert_jobdef( %s )", (Json(_jobdef),) )