在将字符串用作 JSON 对象之前,正确的转义方法是什么
我需要从数据库中的值创建一个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
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)
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()
当然可以!请把你想要翻译的内容发给我,我会帮你把它变得简单易懂。