SQLAlchemy(psycopg2.ProgrammingError)无法适应类型'dict'

时间:2019-06-28 14:04:28

标签: json python-3.x pandas postgresql sqlalchemy

在网络上找不到针对我的问题的解决方案。 我正在尝试使用SQLAlchemy将此pandas df插入Postgresql表

  • 熊猫0.24.2
  • sqlalchemy 1.3.3
  • python 3.7

我的代码的相关部分如下:

engine = create_engine('postgresql://user:pass@host:5432/db')

file = open('GameRoundMessageBlackjackSample.json', 'r', encoding='utf-8')
json_dict = json.load(file)
df = json_normalize(json_dict, record_path='cards', meta=['bet', 'dealerId', 'dealerName', 'gameOutcome', 'gameRoundDuration', 'gameRoundId', 'gameType', 'tableId', 'win'])
df = df[['win', 'betAmount', 'bets']]

df.to_sql('test_netent_data', engine, if_exists='append')

enter image description here

当我尝试将此表加载到sql时,列'bets'的所有内容均按预期工作。但是当我包含它时,出现以下错误:

sqlalchemy.exc.ProgrammingError: (psycopg2.ProgrammingError) can't adapt 
type 'dict'
[SQL: INSERT INTO test_netent_data (index, win, "betAmount", bets) VALUES (%(index)s, %(win)s, %(betAmount)s, %(bets)s)]
[parameters: ({'index': 0, 'win': '2000.00', 'betAmount': '1212112', 'bets': [{'name': '1', 'amount': '1212112'}]}, {'index': 1, 'win': '2000.00', 'betAmount': '1212000', 'bets': [{'name': '1', 'amount': '1212000'}]}, {'index': 2, 'win': '2000.00', 'betAmount': '1212112', 'bets': [{'name': '1', 'amount': '1212112'}]}, {'index': 3, 'win': '2000.00', 'betAmount': '1212000', 'bets': [{'name': '1', 'amount': '1212000'}]}, {'index': 4, 'win': '2000.00', 'betAmount': '1212112', 'bets': [{'name': '1', 'amount': '1212112'}]}, {'index': 5, 'win': '2000.00', 'betAmount': '1212000', 'bets': [{'name': '1', 'amount': '1212000'}]}, {'index': 6, 'win': '2000.00', 'betAmount': '1212112', 'bets': [{'name': '1', 'amount': '1212112'}]}, {'index': 7, 'win': '2000.00', 'betAmount': '1212000', 'bets': [{'name': '1', 'amount': '1212000'}]})]
(Background on this error at: http://sqlalche.me/e/f405)

我已经检查了此列的类型,但是(类型对象)与其他列没有什么不同。香港专业教育学院也试图将其转换为字符串,并得到了一堆其他错误。 我相信应该有一个简单的解决方案,我无法理解。

2 个答案:

答案 0 :(得分:0)

对我来说,更好的方法是将此列表字典解析为单独的列。但是,如果要将列 bets 添加到SQL表中,则需要对其进行转换。您写道这是对象,但它是字典列表。下面是如何将其转换为字符串的代码:

df['bets'] = list(map(lambda x: json.dumps(x), df['bets']))

答案 1 :(得分:0)

只需使用数据框即可

df['bets'] = df['bets'].apply(json.dumps)