在進行urlencode轉換請求的參數時,一直多出一個空格,致使請求參數不正確,多了一個空格,解決方法一種是將dict中key-value鍵值對的value直接定義爲字符串,另外一種是value仍然爲字典,增長一部轉爲json字符,以後再進行編碼,dict轉爲json字符串也要注意空格問題,默認轉成的json字符串仍是有多餘的空格json
1 # -*- coding: utf-8 -*- 2 import json 3 from urllib import parse 4 5 """ 6 @version: v1.0 7 @author: monleylu 8 @time: 2018/2/24 10:35 9 """ 10 urlParam = { 11 "c": { 12 "cc": 3402, 13 "ct": 10, 14 "p": 14588, 15 "ov": 20, 16 "dt": 0, 17 "v": "9.32.1" 18 } 19 } 20 #### 21 # 正常編碼結果應該爲: 22 # c=%7B%22cc%22%3A3402%2C%22ct%22%3A10%2C%22p%22%3A14588%2C%22ov%22%3A20%2C%22dt%22%3A0%2C%22v%22%3A%229.32.1%22%7D 23 # 能夠看到多了個+ 加號 24 ### 25 print("直接對字典進行編碼後結果:\r\n" + parse.urlencode(urlParam)) 26 27 28 29 b = {"cc":3402,"ct":10,"p":14588,"ov":20,"dt":0,"v":"9.32.1"} 30 # 能夠看到默認格式參數化時,會多出一個空格 31 print("使用默認參數轉換dict到json字符串:\r\n" + json.dumps(b)) 32 33 print("非默認參數轉換dict到json字符串:\r\n" + json.dumps(b, separators=(',', ':'))) 34 a = {"c": json.dumps(b, separators=(',', ':'))} 35 print(parse.urlencode(a)) 36 37 #一種解決方法 38 urlParam["c"]=json.dumps((urlParam["c"]),separators=(',', ':')) 39 print("進行編碼後結果:\r\n" + parse.urlencode(urlParam)) 40 41 #另外一種解決方法,這種方法仍然要注意字符串中間的空格,不是太推薦這種方法 42 urlParam = { "c": '{"cc":3402,"ct":10,"p":14588,"ov":20,"dt":0,"v":"9.32.1"}'} 43 print("進行編碼後結果2:\r\n" + parse.urlencode(urlParam))
輸出結果直接對字典進行編碼後結果:c=%7B%27cc%27%3A+3402%2C+%27ct%27%3A+10%2C+%27p%27%3A+14588%2C+%27ov%27%3A+20%2C+%27dt%27%3A+0%2C+%27v%27%3A+%279.32.1%27%7D使用默認參數轉換dict到json字符串:{"cc": 3402, "ct": 10, "p": 14588, "ov": 20, "dt": 0, "v": "9.32.1"}非默認參數轉換dict到json字符串:{"cc":3402,"ct":10,"p":14588,"ov":20,"dt":0,"v":"9.32.1"}c=%7B%22cc%22%3A3402%2C%22ct%22%3A10%2C%22p%22%3A14588%2C%22ov%22%3A20%2C%22dt%22%3A0%2C%22v%22%3A%229.32.1%22%7D進行編碼後結果:c=%7B%22cc%22%3A3402%2C%22ct%22%3A10%2C%22p%22%3A14588%2C%22ov%22%3A20%2C%22dt%22%3A0%2C%22v%22%3A%229.32.1%22%7D進行編碼後結果2:c=%7B%22cc%22%3A3402%2C%22ct%22%3A10%2C%22p%22%3A14588%2C%22ov%22%3A20%2C%22dt%22%3A0%2C%22v%22%3A%229.32.1%22%7D