首页 > 解决方案 > 无法将具有 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","re​​source.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

任何帮助将不胜感激。

标签: pythonmysqldjangopandasgraphql

解决方案


您的列不包含有效的 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 字符串。


推荐阅读