psycopg2.ProgrammingError: can't adapt type 'dict'

Viewed 4025

I have sql class in python which inserts data to my DB. In my table, one column is jsonfield and when I insert data to that table , i get error (psycopg2.ProgrammingError: can't adapt type 'dict') .

I have used json.load , json.loads , json.dump , json.dumps. None of them worked. Even I tried string formatting. It did not work, either.

Any idea how to do?

my demo code is

json_data = {
 "key": "value"
 }
query = """INSERT INTO  table(json_field) VALUES(%s)"""
self.cursor.execute(query, ([json_data,]))
self.connection.commit()

1 Answers

Below block of code worked for me

import psycopg2
import json

json_data = {
 "key": "value"
 }

json_object = json.dumps(json_data, indent = 4)  

query = """INSERT INTO  json_t(field) VALUES(%s)"""

dbConn = psycopg2.connect(database='test', port=5432, user='username')
cursor=dbConn.cursor()
cursor.execute(query, ([json_object,]))
dbConn.commit()
Related