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
Related articles:
Browse by tags:
Browse by language:
Popular articles:
- Web Scraping in Python - The Complete Guide
- Working with Query Parameters in Python Requests
- How to Authenticate with Bearer Tokens in Python Requests
- Building a Simple Proxy Rotator with Kotlin and Jsoup
- The Complete BeautifulSoup Cheatsheet with Examples
- The Complete Playwright Cheatsheet
- Web Scraping using ChatGPT - Complete Guide with Examples