Skip to content

Instantly share code, notes, and snippets.

@groz
Last active September 30, 2016 11:07
Show Gist options
  • Save groz/0ed139130aa3ee6254067d64cc378106 to your computer and use it in GitHub Desktop.
Save groz/0ed139130aa3ee6254067d64cc378106 to your computer and use it in GitHub Desktop.
Url encoded query string parser
#!/usr/bin/env python
"""
Parses application/x-www-form-urlencoded string into a json.
Usage example:
~$ echo "a=1&b=2&a=3" | ./parse_qs.py | jq .
{
"a": [
"1",
"3"
],
"b": "2"
}
"""
import json
from urlparse import parse_qs
import sys
if __name__ == "__main__":
for line in sys.stdin:
line = line.strip().strip('"').strip("'")
# flatten single values
result = {
k: v[0] if len(v) == 1 else v
for k, v in parse_qs(line).iteritems()
}
# format output for jq
print json.dumps(result, separators=[',', ':'], indent=None)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment