When building web applications in Python, you may need to pass array data in a URL to send it between pages or access it on the server. Python provides the urllib module to encode and decode these URLs containing array data.
To create a URL with an array, you can use the
import urllib.parse
my_data = {'an_array': [1, 2, 3]}
url_str = urllib.parse.urlencode(my_data)
print(url_str)
# an_array%5B%5D=1&an_array%5B%5D=2&an_array%5B%5D=3
This encodes the array into a format that can be passed in a URL with separate key/value pairs for each array element.
On the receiving end, you can use
import urllib.parse
url_str = "an_array%5B%5D=1&an_array%5B%5D=2&an_array%5B%5D=3"
data = urllib.parse.parse_qs(url_str)
print(data)
# {'an_array': ['1', '2', '3']}
A few things to note:
To preserve more array structure, you could encode the data as JSON instead using the
In summary, Python's