【问题标题】:Python: How to escape apostrophe in JSON?Python:如何在 JSON 中转义撇号?
【发布时间】:2018-06-12 03:57:35
【问题描述】:

我有 JSON 数据,例如 'Courses Offered': "Economics,World history: survey,Women's history,Other social science course"}

由于Women's history 它给出了错误:

'You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near \'s history,Other social science course"}]

我尝试将' 替换为"'',但没有成功

【问题讨论】:

  • 你试过在引号前加`\`反斜杠吗?
  • 您正在通过字符串连接构建 SQL。不要那样做。曾经。用户参数。
  • 这不是有效的 JSON。 JSON 仅使用双引号字符串。
  • @Tomalak 成功了!!!
  • @Volatil3 贴出你用过的相关代码,我点赞。

标签: python json pymysql


【解决方案1】:

使用 ORM 或其他方式将数据插入数据库,例如查询参数,而不是字符串连接。

【讨论】:

    【解决方案2】:
    dic = {'Courses Offered': "Economics,World history: survey,Women's history,Other social science course"}
    string = dic['Courses Offered'] 
    print(re.sub(r'[\']',"\\'",string))
    >>> Economics,World history: survey,Women\'s history,Other social science course
    

    【讨论】:

    • 这可能会解决直接错误,但它不是解决问题的正确方法。 SQL 永远不应该从字符串构建。在所有情况下都应使用参数。使用参数时,不需要对值进行任何操作。
    猜你喜欢
    • 2010-10-23
    • 2012-03-24
    • 1970-01-01
    • 1970-01-01
    • 2011-01-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多