簡體   English   中英

無法將具有 JSON 列的 Pandas 數據框加載到 mysql 數據庫中

[英]Unable to load a pandas dataframe having a JSON column into mysql database

我有一個 Pandas 數據框,當我在 pycharm 的終端中打印出來時,它看起來像這樣。 這是在 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

任何幫助將不勝感激。

您的列不包含有效的 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 df.to_sql()列表設置列,但由於您使用df.to_sql()進行保存,因此這需要您的數據框具有 SQL 查詢所需的確切數據。 如果你使用你的模型,你可以只分配my_factexception.exception = some_dict ,它會保存為 JSON。 但是您實際上繞過了了解您的模型並知道如何將字典映射到jsonb字段的 Django ORM,因此您必須自己完成。

因此,當您為異常列設置值時,請使用json.dumps(some_dict)創建 json 字符串。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM