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 1.1KB

7 months ago
7 months ago
7 months ago
7 months ago
7 months ago
7 months ago
7 months ago
7 months ago
7 months ago
7 months ago
1234567891011121314151617181920212223242526272829303132333435363738394041
  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. Example: `echo '{"abc":[null,{"zzz":"hello world"}]}' | ./get-json-key.py abc 1 zzz` # -> hello world
  7. """
  8. import fileinput, sys, json, functools
  9. from typing import *
  10. def try_as_obj_then_as_array(data: Any, key: str) -> Any:
  11. try:
  12. # initial attempt, as object
  13. return data[key]
  14. except (KeyError, TypeError):
  15. # fallback, as array
  16. return data[int(key)]
  17. def main(keys: List[str]) -> None:
  18. for line in fileinput.input(files=('-',)):
  19. data = json.loads(line)
  20. try:
  21. val = functools.reduce(lambda acc, x: try_as_obj_then_as_array(acc, x), keys, data)
  22. except Exception as e:
  23. print('indexing json data failed with keys {}: {}\n'.format(' > '.join(keys), e), file=sys.stderr)
  24. raise e
  25. print(val)
  26. if __name__ == '__main__':
  27. if len(sys.argv) < 2:
  28. print(HELP, file=sys.stderr)
  29. sys.exit(1)
  30. main(sys.argv[1:])