【问题标题】:Convert into json转换成json
【发布时间】:2018-05-14 15:05:49
【问题描述】:

SQL 失败:INSERT INTO \"brand\" (\"brand_id\", \"name\", \"notification_email\", \"notification_phone\", \"created_at\", \"updated_at\") 值 (%(0)s, %(1)s, %(2)s, %(3)s, %(4)s, %(5)s)\nPymongo 错误:{\'index\': 0, \'code\': 11000, \'errmsg\': \'E11000 重复键错误集合:f2fretaildev.brand 索引: name_1 复制密钥:{ : \"shyamalas\" }\'}\n版本:1.2.26"

这是使用 djongo (django mongodb orm) 添加数据时重复键的错误

有没有办法将其中的 pymongo 错误作为 json 获取?我尝试了 json.dumps 和 json.loads 都不起作用

【问题讨论】:

  • 看起来您的错误与 JSON 无关,而是 JSON 中的重复数据。 duplicate key error 在这里很重要。
  • 是的,我想解析重复的密钥并将其作为响应发送。有没有办法获得?

标签: python json python-3.x pymongo djongo


【解决方案1】:

问题在于错误消息的 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-05
    • 2020-09-29
    • 1970-01-01
    • 1970-01-01
    • 2016-07-16
    • 2013-06-08
    • 2016-08-01
    • 2020-11-03
    相关资源
    最近更新 更多