问题是错误消息的 JSON 格式不正确。我必须做一些调理;下面的代码只是给你一个方法。它非常脆弱,因为如果错误消息发生变化,它可能会失败 - 您将不得不处理边缘情况。
import json
error_msg = """
FAILED SQL: INSERT INTO \"brand\" (\"brand_id\", \"name\", \"notification_email\", \"notification_phone\", \"created_at\",
\"updated_at\") VALUES (%(0)s, %(1)s, %(2)s, %(3)s, %(4)s, %(5)s)\nPymongo error: {\'index\': 0, \'code\': 11000,
\'errmsg\': \'E11000 duplicate key error collection: f2fretaildev.brand index: name_1 dup key:
{ : \"shyamalas\" }\'}\nVersion: 1.2.26"
"""
key = "Unknown"
try:
mongo_msg = error_msg.split('Pymongo error:')[1].split('Version:')[0].replace('\n','').replace('"','##')\
.replace("'", '"').replace("{ :", " ").replace("## }", "##").replace('##', '')
as_dict = json.loads(mongo_msg)
error_msg = as_dict['errmsg']
value = error_msg.split('key:')[1].strip()
print(error_msg)
print(value)
except:
# Log it, print it, try something different
pass