psycopg2 вставить словарь python как json

Я хочу вставить словарь python в качестве json в мою базу данных postgresql (через python и psycopg2). У меня:

...
thedictionary = {'price money': '', 'name': 'Google', 'color': '', 'imgurl': 'http://www.google.com/images/nav_logo225.png', 'charateristics': 'No Description', 'store': 'google'}
...

cur.execute("INSERT INTO product(store_id, url, price, charecteristics, color, dimensions) VALUES (%d, %s, %s, %d, %s, %s)", (1,  'http://www.google.com', '', thedictionary, 'red', '8.5x11'))

...

и он дает сообщение об ошибке:

    cur.execute("INSERT INTO product(store_id, url, price, charecteristics, color, dimensions) VALUES (%d, %s, %s, %d, %s, %s)", (1,  'http://www.google.com', '', thedictionary, 'red', '8.5x11'))
psycopg2.ProgrammingError: can't adapt type 'dict'

Я не уверен, как продолжить отсюда. Я ничего не могу найти в интернете о том, как это сделать, и я очень новичок в psycopg2.

2 ответов


cur.execute("INSERT INTO product(store_id, url, price, charecteristics, color, dimensions) VALUES (%s, %s, %s, %s, %s, %s)", (1,  'http://www.google.com', '', json.dumps(thedictionary), 'red', '8.5x11'))

это решит вашу проблему. Однако, вы действительно должны хранить ключи и значения в отдельные столбцы. Чтобы получить словарь, сделайте:

cur.execute('select charecteristics from product where store_id = 1')
dictionary = json.loads(cur.fetchone()[0])

надеюсь, что это помогает.


можно использовать psycopg2.extras.Json преобразовать dict в json, который postgre принимает.

from psycopg2.extras import Json

thedictionary = {'price money': '', 
'name': 'Google', 'color': '', 'imgurl': 'http://www.google.com/images/nav_logo225.png', 'charateristics': 'No Description', 'store': 'google'}

item ={
    "store_id":1,
    "url": 'http://www.google.com', 
    "price":'', 
    "charecteristics":Json(thedictionary), 
    "color":'red', 
    "dimensions":'8.5x11'
}

def sql_insert(tableName, data_dict):
    '''
    INSERT INTO product (store_id,  url,  price,  charecteristics,  color,  dimensions)
    VALUES (%(store_id)s, %(url)s, %(price)s, %(charecteristics)s, %(color)s, %(dimensions)s );
    '''
    sql = '''
        INSERT INTO %s (%s)
        VALUES (%%(%s)s );
        '''   % (tableName, ',  '.join(data_dict),  ')s, %('.join(data_dict))
    return sql

tableName = 'product'
sql = sql_insert(tableName, item)

cur.execute(sql, item)

для получения дополнительной информации вы можете увидеть управление документа.

class psycopg2.extras.Json(adapted, dumps=None)

    An ISQLQuote wrapper to adapt a Python object to json data type.

    Json can be used to wrap any object supported by the provided dumps function. If none is provided, the standard json.dumps() is used (simplejson for Python < 2.6; getquoted() will raise ImportError if the module is not available).

    dumps(obj)
    Serialize obj in JSON format.

    The default is to call json.dumps() or the dumps function provided in the constructor. You can override this method to create a customized JSON wrapper.