|
- #!/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:])
-
|