urlencode an array of values

后端 未结 5 1674
半阙折子戏
半阙折子戏 2020-12-13 08:25

I\'m trying to urlencode an dictionary in python with urllib.urlencode. The problem is, I have to encode an array.

The result needs to be:

criterias%         


        
5条回答
  •  南笙
    南笙 (楼主)
    2020-12-13 09:29

    To abstract this out to work for any parameter dictionary and convert it into a list of tuples:

    import urllib
    
    def url_encode_params(params={}):
        if not isinstance(params, dict): 
            raise Exception("You must pass in a dictionary!")
        params_list = []
        for k,v in params.items():
            if isinstance(v, list): params_list.extend([(k, x) for x in v])
            else: params_list.append((k, v))
        return urllib.urlencode(params_list)
    

    Which should now work for both the above example as well as a dictionary with some strings and some arrays as values:

    criterias = ['member', 'issue']
    params = {
        'criterias[]': criterias,
    }
    url_encode_params(params)
    >>'criterias%5B%5D=member&criterias%5B%5D=issue' 
    

提交回复
热议问题