I have a table with a JSONB
field and would like to insert into it using a named dict like so:
sql = "INSERT INTO tbl (id, json_fld) VALUES (%(id)s, %(json_fld)s)"
conn.execute(sql, {'id':1, 'json_fld': {'a':1,'b':false, 'c': 'yes'}});
I tried the answers in this question but those all apply to psycopg2 and NOT psycopg3 and they do not work here (notably I tried):
conn.execute(sql, {'id':1, 'json_fld': json.dumps({'a':1,'b':false, 'c': 'yes'})});
The error remains the same:
psycopg.ProgrammingError: cannot adapt type ‘dict’ using placeholder
‘%s’ (format: AUTO)
2
Answers
You can achieve this in psycopg3 by converting the dictionary to JSON first using
json.dumps
function.Python code to convert
dict
tojsonb
usingpsycopg
JSON adapters described here JSON adaptation section JSON adaptation.This results in: