You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

get-json-key.py 786B

4 years ago
123456789101112131415161718192021222324252627282930
  1. #!/usr/bin/env python3
  2. import fileinput, sys, json, functools
  3. from typing import Union, List
  4. JsonKey = Union[str, int]
  5. def try_int(x: str) -> JsonKey:
  6. try:
  7. return int(x)
  8. except:
  9. return x
  10. def main(indices: List[str]) -> None:
  11. for line in fileinput.input(files=('-',)):
  12. data = json.loads(line)
  13. try:
  14. val = functools.reduce(lambda x, i: x[try_int(i)], indices, data)
  15. except Exception as e:
  16. print('indexing json data failed with keys {}: {}\n'.format(' > '.join(indices), e), file=sys.stderr)
  17. raise e
  18. print(val)
  19. if __name__ == '__main__':
  20. if len(sys.argv) < 2:
  21. print('USAGE: ./get-json-key.py [KEY].. < json-input', file=sys.stderr)
  22. sys.exit(1)
  23. main(sys.argv[1:])