PYTHON parse_str

is this article helpful?
Python replacement for PHP's parse_str [ edit | history ]
s = 'first=value&sec=foo+bar'
import urlparse
print urlparse.parse_qs(s) # {'first': ['value'], 'sec': ['foo bar']}
# 2.6
import urlparse
print urlparse.parse_qs(s) # {'first': 'value', 'sec': 'foo bar'}

# 3.x
import urllib.parse
print urllib.parse.parse_qs(s) # {'first': 'value', 'sec': 'foo bar'}

# < 2.6
import cgi
print cgi.parse_qs(s) # {'first': 'value', 'sec': 'foo bar'}


A more sophisticated implementation that mimics php's exact behavior (with nested arrays, etc). It requires the package (and ordereddict in <= 2.6) and is based on it's parse function. (Tested in Python 2.6)
    from collections import OrderedDict
except ImportError:
    from ordereddict import OrderedDict
from querystring_parser.parser import *
def php_parse_str(query_string, unquote=True):
    def recurse( pair, out=None, indent=0 ):
        if isinstance(pair,dict):
            (k, v) = pair.popitem()
            if out is None:
                if isinstance(k,int) or k == '':
                    out = []
                    out = OrderedDict()
            if isinstance(out,list) and (k == ''):
                out.append( recurse(v,indent=indent+1) )
            elif isinstance(out,list) and (k != ''):
                out = dict(enumerate(out)) # merge list with dict
                out[k] = recurse(v, out.get(k),indent=indent+1)
            elif isinstance(out,dict) and k == '':
                numeric_indices = [k for k in out.keys() if isinstance(k,int)]
                out[1+max(numeric_indices) if numeric_indices else 0] = recurse(v, out.get(k))
            elif isinstance(out,dict):
                out[k] = recurse(v, out.get(k),indent=indent+1)
                return recurse({k:v},indent=indent+1) # overwriting scalar out by dict or list
            return out
        return pair

    plist = []
    if query_string == "":
        return mydict
    for element in query_string.split("&"):
            if unquote:
                (var, val) = element.split("=")
                var = urllib.unquote_plus(var)
                val = urllib.unquote_plus(val)
                (var, val) = element.split("=")
        except ValueError:
            raise MalformedQueryStringError
        plist.append(parser_helper(var, val))

    out = OrderedDict()
    for pair in plist:
        out = recurse(pair,out)
    return out

print "Runing tests"

x = php_parse_str("foo=1")
assert x == dict(foo=1), x 

x = php_parse_str("foo[]=1")
assert x == dict(foo=[1]), x 

x = php_parse_str("foo[bar]=1")
assert x == dict(foo=dict(bar=1)), x 

x = php_parse_str("foo=1&foo[]=2")
assert x == dict(foo=[2]), x 

x = php_parse_str("foo[]=1&foo=2")
assert x == dict(foo=2), x 

x = php_parse_str("foo=1&foo[bar]=3&foo[]=2")
assert x == dict(foo={'bar':3,0:2}), x 

x = php_parse_str("foo=1&foo[]=3&foo[bar]=2")
assert x == dict(foo={'bar':2,0:3}), x 

print "Done"

PHP parse_str

PHP original manual for parse_str [ show | ]


(PHP 4, PHP 5)

parse_strParses the string into variables


void parse_str ( string $str [, array &$arr ] )

Parses str as if it were the query string passed via a URL and sets variables in the current scope.

Note: To get the current QUERY_STRING, you may use the variable $_SERVER['QUERY_STRING']. Also, you may want to read the section on variables from external sources.

Note: The magic_quotes_gpc setting affects the output of this function, as parse_str() uses the same mechanism that PHP uses to populate the $_GET, $_POST, etc. variables.



The input string.


If the second parameter arr is present, variables are stored in this variable as array elements instead.

Return Values

No value is returned.


Version Description
4.0.3 The arr parameter was added


Example #1 Using parse_str()

$first;  // value
echo $arr[0]; // foo bar
echo $arr[1]; // baz

$output['first'];  // value
echo $output['arr'][0]; // foo bar
echo $output['arr'][1]; // baz


See Also