我必須從數據庫值創建JSON字符串並將其再次推回到數據庫。我的Python代碼是:在將字符串用作json對象之前,轉義字符串的正確方法是什麼
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輸出與輸入相同?
你爲什麼不使用[內置JSON編碼器](http://docs.python.org/library/json.html)? – Tomalak