URI Parsing
Name-Value Collection
Web Development
Programming
Data Structures

Parse a URI String into Name-Value Collection

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

When developing applications or APIs, understanding and interacting with Uniform Resource Identifiers (URIs) is crucial. A URI string is a compact sequence of characters that identifies an abstract or physical resource. A typical URI format contains various components such as schema, authority, path, query, and fragment. Among these, the query component, which is often a string of name-value (key-value) pairs, is particularly important. This component starts after a '?' in the URI and can impact the resource retrieval process significantly. Parsing a URI string into a name-value collection is a vital operation for accessing these parameters and effectively utilizing their values in program logic.

Understanding URI Parsing

Parsing a URI means breaking it down into its constituent parts, especially focusing on the query string. The query string generally appears after a question mark '?' in the URL and is composed of key-value pairs. Each pair is separated by an '&' symbol, and the key is separated from the value by an '='. The purpose of parsing is to extract these name-value pairs into a more usable format such as a dictionary or map.

Example URI:

 
http://example.com/page?param1=value1&param2=value2

In this example, the query string is param1=value1&param2=value2. Parsing this would ideally result in a collection where param1 maps to value1 and param2 maps to value2.

Technical Procedure

The procedure for parsing a URI into a name-value collection typically involves the following steps:

  1. Identify the Query String: This involves finding the substring that follows the '?' character in the URI.
  2. Split the Query String: Use the '&' character to split the query into individual key-value pairs.
  3. Split Key-Value Pairs: For each pair, split the string by the '=' character to separate the key from the value.
  4. Decode URL Encoding: Since URL encoding (like %20 for space) might be used in URIs, values need to be decoded into readable formats.
  5. Store in Collection: Lastly, store these as entries in a suitable collection, ensuring repeated keys are appropriately handled if necessary.

Practical Example

Here is a basic example using Python:

python
1from urllib.parse import parse_qs, urlparse
2
3uri = "http://example.com/page?param1=value1&param2=value2"
4parsed_url = urlparse(uri)
5query_string = parsed_url.query
6
7# parse_qs returns a dictionary where each key maps to a list of values
8params = parse_qs(query_string)
9
10print(params) # Output: {'param1': ['value1'], 'param2': ['value2']}

Handling URL Encoding

Be mindful of URL encoding in parameters. For example, if the value includes spaces or other special characters, these will be encoded with characters like %20. Libraries like urllib.parse in Python automatically handle these encodings.

Special Considerations

  1. Boolean Flags: Sometimes, a key may appear without a value and might be used as a boolean flag.
  2. Repeated Parameters: Often, parameters can be repeated, implying a list of values for the same key.

Tabulated Summary of Key Parsing Aspects

ComponentDescriptionExample
SchemaProtocol used in the URI (e.g., http)http from http://example.com
AuthorityInformation on authority partexample.com from http://example.com
PathResource path on the server/page from http://example.com/page
Query StringParameters for reference or lookupparam1=value1&param2=value2 from http://example.com/page?param1=value1&param2=value2

Conclusion

Parsing URI strings into name-value collections is essential for efficiently handling user inputs from web URLs and for internal navigation and logic within applications. Real-world situations often complicate URI structures and their parsing, requiring developers to handle variabilities in the encoding, value types, and parameter repetitions effectively. With modern programming libraries, developers can streamline much of this process, focusing on ensuring that all edge cases and potential errors are managed effectively.


Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.