在将字符串用作json对象之前,转义字符串的正确方法是什么

时间:2011-09-22 09:25:50

标签: python json serialization

我必须从数据库值创建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输出与输入相同?

3 个答案:

答案 0 :(得分:3)

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()

答案 1 :(得分:0)

答案 2 :(得分:0)

只需使用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)