Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should I encode dictionaries into HTTP GET query strings?

An HTTP GET query string is a ordered sequence of key/value pairs:

?spam=eggs&spam=ham&foo=bar

Is, with certain semantics, equivalent to the following dictionary:

{'spam': ['eggs', 'ham'], 'foo': bar}

This happens to work well for boolean properties of that page being requested:

?expand=1&expand=2&highlight=7&highlight=9
{'expand': [1, 2], 'highlight': [7, 9]}

If you want to stop expanding the element with id 2, just pop it out of the expand value and urlencode the query string again. However, if you've got a more modal property (with 3+ choices), you really want to represent a structure like so:

{'highlight_mode': {7: 'blue', 9: 'yellow'}}

Where the values to the corresponding id keys are part of a known enumeration. What's the best way to encode this into a query string? I'm thinking of using a sequence of two-tuples like so:

?highlight_mode=(7,blue)&highlight_mode=(9,yellow)

Edit: It would also be nice to know any names that associate with the conventions. I know that there may not be any, but it's nice to be able to talk about something specific using a name instead of examples. Thanks!

like image 431
cdleary Avatar asked Jan 11 '09 00:01

cdleary


1 Answers

The usual way is to do it like this:

highlight_mode[7]=blue&highlight_mode[9]=yellow

AFAIR, quite a few server-side languages actually support this out of the box and will produce a nice dictionary for these values.

like image 107
Konrad Rudolph Avatar answered Oct 15 '22 14:10

Konrad Rudolph