使用python在PostgreSQL中插入Python字典

时间:2018-10-20 09:03:52

标签: python json postgresql psycopg2

需要帮助,使用python将JSON文件数据插入到PostgreSQL的JSON列中

这是我的代码:

import psycopg2 
import simplejson as json

from psycopg2.extras import Json

with open(r'\*.json') as json_data:
data= json.load(json_data)

def insert_into_table(data):
# preparing json data for insertion
for key, value in data.items():
   print(key)

cols = data.keys()
vals = [data[x] for x in cols]

l = [(c, v) for c, v in data.items()]
columns = ','.join([t[0] for t in l])
values = tuple([t[1] for t in l])

keys = data.keys()
columns = ','.join(keys)
values = ','.join(['%({})s'.format(k) for k in keys])

listkey = list(data)

with psycopg2.connect(database='postgres', user='postgres', password='postgres', host='localhost') as conn:
    with conn.cursor() as cursor:

        cursor.execute("""INSERT INTO public.cluster(clustring) VALUES (%s::json)""", ([listkey[1]]))

        conn.commit()

insert_into_table(data)
  

错误:   第1行:将其插入public.cluster(clustring)值('clustring ...                                                             ^   详细信息:令牌“字符串”无效。   语境:JSON数据,第1行:clustring

0 个答案:

没有答案