首页 > 解决方案 > 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 但这不是按照要求。

标签: python-3.xurlencode

解决方案


我又添加了一个这样的“如果”条件:

if (c=='uniqueIdentifier'):
  updatedV1 += quote(c) + '=[' + quote(str(d[0])) + '], '
if (c!='uniqueIdentifier'):
  updatedV1 += quote(c) + '=' + quote(str(d)) + ', '

按预期工作。

谢谢!


推荐阅读