python处理dict转json,字符串中存在空格问题,导致url编码时,存在多余字符

时间:2023-12-30 14:27:20

在进行urlencode转换请求的参数时,一直多出一个空格,导致请求参数不正确,多了一个空格,解决方法一种是将dict中key-value键值对的value直接定义为字符串,另一种是value仍然为字典,增加一部转为json字符,之后再进行编码,dict转为json字符串也要注意空格问题,默认转成的json字符串还是有多余的空格

 # -*- coding: utf-8 -*-
import json
from urllib import parse """
@version: v1.0
@author: monleylu
@time: 2018/2/24 10:35
"""
urlParam = {
"c": {
"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
# 可以看到多了个+ 加号
###
print("直接对字典进行编码后结果:\r\n" + parse.urlencode(urlParam)) b = {"cc":3402,"ct":10,"p":14588,"ov":20,"dt":0,"v":"9.32.1"}
# 可以看到默认格式参数化时,会多出一个空格
print("使用默认参数转换dict到json字符串:\r\n" + json.dumps(b)) print("非默认参数转换dict到json字符串:\r\n" + json.dumps(b, separators=(',', ':')))
a = {"c": json.dumps(b, separators=(',', ':'))}
print(parse.urlencode(a)) #一种解决方法
urlParam["c"]=json.dumps((urlParam["c"]),separators=(',', ':'))
print("进行编码后结果:\r\n" + parse.urlencode(urlParam)) #另一种解决方法,这种方法仍然要注意字符串中间的空格,不是太推荐这种方法
urlParam = { "c": '{"cc":3402,"ct":10,"p":14588,"ov":20,"dt":0,"v":"9.32.1"}'}
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