python - 含中文JSON未能按期待進行dumps,(\xxx\xxx\xxx)?
問題描述
使用Python的requests庫仿寫自定義web客戶端中,遇到含中文的內容提交后異常的問題。
經Fiddler查看該請求的raw,可知官方客戶端的提交內容為:
...{'jsonstr':'{'pageindex':1,'keyword':'張三'}'}
而自行定義的客戶端提交內容為:
...{'jsonstr': '{’pageindex’: 1,’keyword’: ’xe5xbcxa0xe4xb8x89’'}
自行定義客戶端的腳本大概為:
# -*- coding: utf-8 -*-keyword =’張三’jsonstr ={ 'pageindex':1,'keyword':keyword}data = {'jsonstr':str(jsonstr)}r = requests.post(url, data =json.dumps(data))
嘗試 data =json.dumps(data, ensure_ascii=False) 但狀況依舊。如果keyword為數字則一切正常。使用平臺為win7.
問題解答
回答1:# coding: utf-8import jsonkeyword = ’張三’jsonstr ={ 'pageindex':1,'keyword':keyword}data = {'jsonstr': json.dumps(jsonstr, ensure_ascii=False)}r = requests.post(url, json=data)
