2011-09-22 94 views
1

我必須從數據庫值創建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輸出與輸入相同?

+0

你爲什麼不使用[內置JSON編碼器](http://docs.python.org/library/json.html)? – Tomalak

回答

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

謝謝@Ignacio Vazquez-Abrams您所做的一個重要更正是在查詢中將%d更改爲%s。我在%d處得到'ValueError:不支持的格式字符'd'(0x64)在索引32'處 – jerrymouse

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) 
相關問題