Skip to content

Instantly share code, notes, and snippets.

@mtth
Last active September 26, 2022 07:01
Show Gist options
  • Save mtth/0d3aadfb342690c25ea58cd8b1084035 to your computer and use it in GitHub Desktop.
Save mtth/0d3aadfb342690c25ea58cd8b1084035 to your computer and use it in GitHub Desktop.
Rest.li encode: a simpler way to encode Rest.Li query parameters.
#!/usr/bin/env python
# encoding: utf-8
"""Rest.li encode: a simpler way to encode Rest.Li query parameters.
Usage:
restli-encode.py [JSON]
Arguments:
JSON JSON string. Will read stdin if unspecified.
Options:
-h --help Show this message and exit.
-v --version Show version and exit.
Examples:
restli-encode '{"foo": 1, "bar": [1, 2, 3]}'
curl http://localhost:8000/api -Gd $(restli-encode <data.json)
"""
from docopt import docopt
from json import loads
from urllib import quote_plus
import re
import sys
__version__ = '0.1.0'
def _encode(data):
"""Encoding recursion helper.
:param data: Decoded JSON data.
"""
if isinstance(data, dict):
return (
('.%s%s' % (key, suffix), encoded_value)
for key, value in data.items()
for suffix, encoded_value in _encode(value)
)
elif isinstance(data, list):
return (
('[%s]%s' % (index, suffix), encoded_value)
for index, value in enumerate(data)
for suffix, encoded_value in _encode(value)
)
else:
# String or number (since we assume data is valid JSON).
return [('', quote_plus(str(data)))]
def encode(data):
"""Encode data suitably for Rest.Li GET requests.
:param data: Decoded JSON data.
"""
if not isinstance(data, dict):
raise ValueError('Top level entity must be an object.')
return '&'.join('%s=%s' % (k.lstrip('.'), v) for (k, v) in _encode(data))
def main():
"""Entry point."""
args = docopt(__doc__, version=__version__)
try:
sys.stdout.write(encode(loads(args['JSON'] or sys.stdin.read())))
except ValueError as err:
sys.stderr.write('Invalid JSON. %s\n' % (err, ))
sys.exit(1)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment