python-3.x - json到python中规范请求的url编码
问题描述
我正在使用 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%3DuniqueIdentifierId=storeDetailType%7D%5D¤cyt2TINR=DetailTmer= 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 但这不是按照要求。
解决方案
我又添加了一个这样的“如果”条件:
if (c=='uniqueIdentifier'):
updatedV1 += quote(c) + '=[' + quote(str(d[0])) + '], '
if (c!='uniqueIdentifier'):
updatedV1 += quote(c) + '=' + quote(str(d)) + ', '
按预期工作。
谢谢!
推荐阅读
- reactjs - 反应 gatsby 中的 UseState Hooks
- azure - 为什么在 Azure 中“捕获”VM 的映像会阻止 VM 被使用?
- prometheus - 如何在普罗米修斯中减去两个日期?
- autodesk-forge - 如何使用设计自动化 API 从上传的 AutoCAD 文件中提取元数据?
- c - 捕获通过取消引用指针获得的变量可以是原子的吗?
- node.js - 能够通过 curl 调用 api,但是从 nodejs 调用时相同的 api 挂起
- c# - 是否可以在 FluentValidation 中重用默认消息?
- python - 如何将多个发布者发布给一个订阅者?
- powershell - 查找 Windows 快捷方式的高级选项详细信息
- java - 如何为空哈希图添加junit测试用例