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.

40 lines
999B

  1. #!/usr/bin/env python3
  2. HELP = """
  3. USAGE:
  4. [stdin] | ./get-json-key.py [KEY]..
  5. KEY can be a string key (object) or integer index (array), the program will try both
  6. """
  7. import fileinput, sys, json, functools
  8. from typing import *
  9. def try_as_obj_then_as_array(data: Any, key: str) -> Any:
  10. try:
  11. # initial attempt, as object
  12. return data[key]
  13. except (KeyError, TypeError):
  14. # fallback, as array
  15. return data[int(key)]
  16. def main(keys: List[str]) -> None:
  17. for line in fileinput.input(files=('-',)):
  18. data = json.loads(line)
  19. try:
  20. val = functools.reduce(lambda acc, x: try_as_obj_then_as_array(acc, x), keys, data)
  21. except Exception as e:
  22. print('indexing json data failed with keys {}: {}\n'.format(' > '.join(keys), e), file=sys.stderr)
  23. raise e
  24. print(val)
  25. if __name__ == '__main__':
  26. if len(sys.argv) < 2:
  27. print(HELP, file=sys.stderr)
  28. sys.exit(1)
  29. main(sys.argv[1:])