Created
November 12, 2018 07:03
-
-
Save zh4n7wm/ed36d004d76e009473e71c0196d80e99 to your computer and use it in GitHub Desktop.
just like https://github.com/antonmedv/fx
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 | |
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