Last active
September 30, 2016 11:07
-
-
Save groz/0ed139130aa3ee6254067d64cc378106 to your computer and use it in GitHub Desktop.
Url encoded query string parser
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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