Search code examples
jsonpostgresqlpsycopg2jsonb

How to call a function with json parameter in Postgres


I have to pass a json object to a function but it's not working:

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

TypeError: 'module' object is not callable

Alternatively:

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

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

Solution

  • You can use the wrapper psycopg2.extras.Json(adapted, dumps=None), example:

    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),) )