Skip to content

Instantly share code, notes, and snippets.

@zh4n7wm
Created November 12, 2018 07:03
Show Gist options
  • Save zh4n7wm/ed36d004d76e009473e71c0196d80e99 to your computer and use it in GitHub Desktop.
Save zh4n7wm/ed36d004d76e009473e71c0196d80e99 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
import sys
import json
import types
def usage():
print('usage:')
print(
"""\techo '{"foo": [{"bar": "value"}]}' | """
f'{sys.argv[0]} <python expression>'
)
print(f'\tcat json-file | {sys.argv[0]} <python expression>')
print(f'\tcurl http://json-api | {sys.argv[0]} <python expression>')
sys.exit()
def show(obj):
print(json.dumps(obj, indent=4, ensure_ascii=False))
def load_json():
data = None
try:
data = json.load(sys.stdin)
except json.decoder.JSONDecodeError:
usage()
return data
def exec_function(fn, this):
return fn(this)
def main():
exprs = sys.argv[1:]
this = load_json()
if not this:
usage()
for expr in exprs:
result = eval(expr)
if type(result) == types.FunctionType:
result = exec_function(result, this)
this = result
show(this)
return this
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment