Just convert the dict type to json_str, use json.dumps(adict)
.
import pandas as pd
import json
import psycopg2
from sqlalchemy import create_engine
engine_nf = create_engine('postgresql+psycopg2://user:password@192.168.100.120:5432/database')
sql_read = lambda sql: pd.read_sql(sql, engine_nf)
sql_execute = lambda sql: pd.io.sql.execute(sql, engine_nf)
sql = '''
CREATE TABLE if not exists product (
store_id int
, url text
, price text
, charecteristics json
, color text
, dimensions text
)
'''
_ = sql_execute(sql)
thedictionary = {'price money': '$1', 'name': 'Google',
'color': '', 'imgurl': 'http://www.google.com/images/nav_logo225.png',
'charateristics': 'No Description',
'store': 'google'}
sql = '''
INSERT INTO product(store_id, url, price, charecteristics, color, dimensions)
VALUES (%d, '%s', '%s', '%s', '%s', '%s')
''' % (1, 'http://www.google.com', '$20',
json.dumps(thedictionary), 'red', '8.5x11')
sql_execute(sql)
sql = '''
select *
from product
'''
df = sql_read(sql)
df
# store_id url price charecteristics color dimensions
# 0 1 http://www.google.com $20 {'price money': '$1', 'name': 'Google', 'color... red 8.5x11
charecteristics = df['charecteristics'].iloc[0]
type(charecteristics)
# dict
In fact, I like another way to dump data to postgres.
import io
import csv
def df2db(df_a, table_name, engine):
output = io.StringIO()
# ignore the index
df_a.to_csv(output, sep='\t', index = False, header = False, quoting=csv.QUOTE_NONE)
output.getvalue()
# jump to start of stream
output.seek(0)
#engine ---- from sqlalchemy import create_engine
connection = engine.raw_connection()
cursor = connection.cursor()
# null value become ''
cursor.copy_from(output,table_name,null='')
connection.commit()
cursor.close()
df = sql_read('select * from product')
type(df.charecteristics.iloc[0])
df.charecteristics = df.charecteristics.map(json.dumps)
# dump pandas DataFrame to postgres
df2db(df, 'product', engine_nf)
df_end = sql_read('select * from product')
