【问题标题】:What is the right method of escaping string before using it as json object在将字符串用作json对象之前转义字符串的正确方法是什么
【发布时间】:2011-09-22 09:25:49
【问题描述】:

我必须从数据库值创建 JSON 字符串并将其再次推送回数据库。我的 Python 代码是:

json = "{"
for row in cursor_mysql:
    #mainkey = row[0]
    #name = row[1]
    #value = row[2]
    mainkey = """"  " \n \ /  """    #for testing only
    name = """    {} " \r \t  """    #for testing only
    value = """  ' " \ &      """    #for testing only
    json += """"%s":{"name":"%s","value":"%s"},""" % (re.escape(mainkey), re.escape(name), re.escape(value))

json = json[:-1]
json += "}"
#print json
query = """UPDATE table SET json = '%s' WHERE id = '%d' RETURNING id""" %  (json, rowId)
cursor_postgres.execute(query)
conn_postgres.commit()
insertId = cursor_postgres.fetchone()[0]

当周围没有恶意字符时,此代码效果很好。但是,如上面的测试用例中那样,当使用非字母数字值时,它就不起作用了。

进入我的数据库的错误 JSON 是:

{
    """ 
 \ /   ": {
        "name": " {} "","value":"'"  "
    },
    """ 
 \ /   ": {
        "name": " {} "","value":"'"  "
    }
}

如何清理字符串,以便反序列化时 json 输出与输入相同?

【问题讨论】:

标签: python json serialization


【解决方案1】:
import json

data = json.dumps(BIG_STRUCTURE_GOES_HERE)
query = """UPDATE table SET json = %s WHERE id = %s RETURNING id"""
cursor_postgres.execute(query, (data, rowId))
conn_postgres.commit()

【讨论】:

  • 感谢@Ignacio Vazquez-Abrams 您所做的一项重要更正是将查询中的 %d 更改为 %s。我收到了 ValueError: unsupported format character 'd' (0x64) at index 32 和 %d
【解决方案2】:
【解决方案3】:

只需使用json 库:

import json
mainkey = """"  " \n \ /  """    #for testing only
name = """    {} " \r \t  """    #for testing only
value = """  ' " \ &      """    #for testing only
d = {mainkey: {"name": name, "value": value}}
jsonValue = json.dumps(d)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-24
    • 1970-01-01
    • 2014-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-13
    相关资源
    最近更新 更多