From 35e98ccd563b2d6bc4a3b898ffcdb156e397dbf6 Mon Sep 17 00:00:00 2001 From: Jonathan Strong Date: Tue, 10 Mar 2020 20:51:08 -0400 Subject: [PATCH] initial commit --- get-json-key.py | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100755 get-json-key.py diff --git a/get-json-key.py b/get-json-key.py new file mode 100755 index 0000000..7cc0b4d --- /dev/null +++ b/get-json-key.py @@ -0,0 +1,30 @@ +#!/usr/bin/env python3 + +import fileinput, sys, json, functools +from typing import Union, List + +JsonKey = Union[str, int] + +def try_int(x: str) -> JsonKey: + try: + return int(x) + except: + return x + +def main(indices: List[str]) -> None: + for line in fileinput.input(files=('-',)): + data = json.loads(line) + try: + val = functools.reduce(lambda x, i: x[try_int(i)], indices, data) + except Exception as e: + print('indexing json data failed with keys {}: {}\n'.format(' > '.join(indices), e), file=sys.stderr) + raise e + print(val) + +if __name__ == '__main__': + if len(sys.argv) < 2: + print('USAGE: ./get-json-key.py [KEY].. < json-input', file=sys.stderr) + sys.exit(1) + main(sys.argv[1:]) + +