【发布时间】:2021-01-27 16:19:37
【问题描述】:
我正在使用 urllib 包。我正在尝试将我从邮递员填充为 JSON 的嵌套 JSON 编码。
对于解码,我使用的是网站:“https://www.urldecoder.io/”
我的代码编码正确,唯一的问题是两次添加“uniqueIdentifier”。我不需要第二个,即在我的结果中加粗。
有效载荷:
{"accessId": "438kjhkjh",
"storeDetail": {
"storeIdType": "shop",
"storeId": "check"
},
"catalogueDetails": [
{
"brand": "brand",
"uniqueIdentifier": ["uniqueIdentifier"],
"uniqueIdentifierType": "uniqueIdentifierType"
}
],
"merchantId": "T123T",
"transactionTimeout": "900",
"currencyCode": "INR"}
我的代码:
from urllib.parse import quote
def format_parameters(params):
param_string = ''
updatedV = ''
updatedV1 = ''
try:
for k, v in sorted(params.items()):
# print("k:: ",k)
# print("v:: ",v)
if(k=='storeDetail'):
for a,b in v.items():
updatedV += quote(a) + '=' + quote(str(b)) + ', '
updatedV = updatedV[:-2]
updatedV = "{"+updatedV+"}"
param_string += quote(k) + '=' + quote(str(updatedV)) + '&'
elif(k=='catalogueDetails'):
for c,d in v[0].items():
if (c=='uniqueIdentifier'):
updatedV1 += quote(c) + '=[' + quote(str(d[0])) + '], '
updatedV1 += quote(c) + '=' + quote(str(d)) + ', '
print(updatedV1)
updatedV1 = updatedV1[:-2]
updatedV1 = "[{"+updatedV1+"}]"
param_string += quote(k) + '=' + quote(str(updatedV1)) + '&'
else:
param_string += quote(k) + '=' + quote(str(v)) + '&'
except Exception as ex:
print (ex)
param_string = param_string[:-1]
return param_string.replace('+', '%20').replace('*', '%2A').replace('%7E', '~').replace("%27","")
编码输出
accessId=438kjhkjh&catalogueDetails=%5B%7Bbrand%3Dbrand%2C%20uniqueIdentifier%3D%5BuniqueIdentifier%5D%2C%20uniqueIdentifier%3D%255B%2527uniqueIdentifier%2527%255D%2C%20uniqueIdentifierType%3DuniqueIdentifierType%7D%&&¤cytCode=INRmerchanId=5D¤cytCode= T123T&storeDetail=%7BstoreIdType%3Dshop%2C%20storeId%3Dcheck%7D&transactionTimeout=900
通过“https://www.urldecoder.io/”解码输出
accessId=438kjhkjh&catalogueDetails=[{brand=brand, uniqueIdentifier=[uniqueIdentifier], uniqueIdentifier=%5B%27uniqueIdentifier%27%5D, uniqueIdentifierType=uniqueIdentifierType}]¤cyCode=INR&merchantId=T123T&storeDetail={storeIdType =shop, storeId=check}&transactionTimeout=900
注意:
这是我的要求,这也是我做一些手工工作的原因,我尝试了 urllib,但那不符合要求。
【问题讨论】:
标签: python-3.x urlencode