python - 无法将具有 JSON 列的熊猫数据框加载到 mysql 数据库中
问题描述
当我在 pycharm 的终端中打印出来时,我有一个看起来像这样的 pandas 数据框。这是在一个 django 项目中
` exception recommendation time_dimension_id
0 {'exception': []} 0 217
1 {'exception': []} 0 218
2 {'exception': []} 0 219
3 {'exception': []} 546 220
4 {'exception': []} 2876 221
5 {'exception': []} 7855 222
6 {'exception': [{'error... , 5041 223
7 {'exception': []} 57 224
8 {'exception': []} 0 225
9 {'exception': []} 0 226
10 {'exception': []} 0 227
11 {'exception': []} 108 228
12 {'exception': []} 0 229
13 {'exception': []} 12 230
14 {'exception': []} 0 231
15 {'exception': []} 0 232
16 {'exception': []} 0 233
17 {'exception': []} 0 234
18 {'exception': []} 0 235
19 {'exception': []} 0 236
20 {'exception': []} 0 237
21 {'exception': []} 0 238
22 {'exception': []} 0 239
23 {'exception': []} 0 240
`
我尝试使用以下代码将此数据框插入到表中。
connection = engine.connect()
df.to_sql('table_name', con=connection, if_exists='append', index=False)
然后,我收到以下错误
graphql.error.located_error.GraphQLLocatedError:(MySQLdb._exceptions.OperationalError)(3140,'无效的 JSON 文本:“缺少对象成员的名称。”在列 \'fact_exception.exception\' 的值中的位置 1。')[ SQL: 'INSERT INTO fact_exception (exception, Recommendation, time_dimension_id) VALUES (%s, %s, %s)'] [参数: (({'exception': []}, 0, 217), ({'exception' : []}, 0, 218), ({'exception': []}, 0, 219), ({'exception': []}, 546, 220), ({'exception': []}, 2876, 221), ({'exception': []}, 7855, 222), ({'exception': [{'error': '', 'fatal': 'com.materiall.recommender.cache.MetaLU: 58 - 无法为 express_com-u1456154309768com.materiall.conn 加载 metaLU ...(截断 6923 个字符)...“resource.type”:"index_or_alias","resource.id":"null","index_uuid":" na","index":"null"},"status":404}\n', 'time_stamp': '2020-02-11T06:26:23,694'}]}, 5041, 223), ({'exception' : []}, 57, 224) ... 显示 24 个绑定参数集中的 10 个 ... ({'exception': []}, 0, 239), ({'exception': []}, 0, 240))](此错误的背景:http ://sqlalche.me/e/e3q8 )
在用于按列创建数据框的相关代码下方
fact_excep["exception"] = excep_df_column #this is a list of dictionaries
fact_excep["recommendation"] = recommendation_col #this is a list integers
fact_excep["time_dimension_id"] = time_dimension_id_col #this is a list integers
# print(fact_excep)
connection = engine.connect()
fact_excep.to_sql("fact_exception", con=connection, if_exists="append", index=False)
response = "fact_exception data created"
return response
下面是模型
class FactException (models.Model): #this is the model
fact_exception_id = models.AutoField(primary_key=True)
time_dimension_id = models.ForeignKey(
TimeDimension, null=False, blank=True, db_column="time_dimension_id", on_delete=models.CASCADE)
recommendation = models.IntegerField()
exception = JSONField(null=True, blank=True)
objects = models.Manager()
class Meta:
db_table = 'fact_exception'
def __int__(self):
return self.fact_exception_id
任何帮助将不胜感激。
解决方案
您的列不包含有效的 JSON:
{'exception': [{'error': '', 'fatal': 'com.materiall.recommender.cache.MetaLU:58 - Cannot Load metaLU for express_com-u1456154309768com.materiall.conn...'}]}
# and
{'exception': []}
无效,因为键和字符串有单引号,这在 JSON 中无效。您应该使用双引号,并且整个列应该是字符串:
'{"exception": [{"error": "", "fatal": "com.materiall.recommender.cache.MetaLU:58 - Cannot Load metaLU for express_com-u1456154309768com.materiall.conn..."}]}'
# and
'{"exception": []}'
您正在使用 python dicts 列表设置列,但由于您使用df.to_sql()
保存,这需要您的数据框具有 SQL 查询所需的确切数据。如果您正在使用您的模型,您可以只分配my_factexception.exception = some_dict
并将它保存为 JSON。但是你基本上绕过了 Django ORM,它知道你的模型并且知道如何将字典映射到jsonb
字段,所以你必须自己做。
因此,当您为异常列设置值时,请使用json.dumps(some_dict)
创建 json 字符串。
推荐阅读
- greenplum - 在Greenplum函数中将空数组作为参数传递
- python - 有没有办法使用一串变量名作为函数的输入?
- ssl - JDK7 的 SSL 握手失败警报
- python - 如何检查是否在 Python 中同时释放了 2 个键?
- java - 在 jboss EAP 7.2 中部署两个具有不同上下文的相同 Web 应用程序时出错
- python - 出现错误“AttributeError:模块'tensorflow'没有属性'contrib'”
- c# - 无法从“System.Drawing.Bitmap”转换为“byte[]”
- linux - 当我的服务器服务在 systemd 中重新启动时如何重新启动蓝牙服务
- node.js - 无法使用带有 Typescipt 的 multer 上传文件?
- c# - 在 Azure Devops Pipeline 中使用 MSBuild 构建和发布 MVC4 应用程序