urlencode an array of values

后端 未结 5 1668
半阙折子戏
半阙折子戏 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:08

    Listcomp of values:

    >>> criterias = ['member', 'issue']
    >>> urllib.urlencode([('criterias[]', i) for i in criterias])
    'criterias%5B%5D=member&criterias%5B%5D=issue'
    >>> 
    
    0 讨论(0)
  • 2020-12-13 09:11

    The solution is far simpler than the ones listed above.

    >>> import urllib
    >>> params = {'criterias[]': ['member', 'issue']}
    >>> 
    >>> print urllib.urlencode(params, True)
    criterias%5B%5D=member&criterias%5B%5D=issue
    

    Note the True. See http://docs.python.org/library/urllib.html#urllib.urlencode the doseq variable.

    As a side note, you do not need the [] for it to work as an array (which is why urllib does not include it). This means that you do not not need to add the [] to all your array keys.

    0 讨论(0)
  • 2020-12-13 09:13

    You can use a list of key-value pairs (tuples):

    >>> urllib.urlencode([('criterias[]', 'member'), ('criterias[]', 'issue')])
    'criterias%5B%5D=member&criterias%5B%5D=issue'
    
    0 讨论(0)
  • 2020-12-13 09:14

    as aws api defines its get url: params.0=foo&params.1=bar

    however, the disadvantage is that you need to write code to encode and decode by your own, the result is: params=[foo, bar]

    0 讨论(0)
  • 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' 
    
    0 讨论(0)
提交回复
热议问题