python处理dict转json,字符串中存在空格问题,导致url编码时,存在多余字符
在进行urlencode转换请求的参数时,一直多出一个空格,导致请求参数不正确,多了一个空格,解决方法一种是将dict中key-value键值对的value直接定义为字符串,另一种是value仍然为字典,增加一部转为json字符,之后再进行编码,dict转为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