jsonpointer 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. #!/tmp/build/80754af9/jsonpointer_1615660556387/_h_env_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_pl/bin/python
  2. # -*- coding: utf-8 -*-
  3. from __future__ import print_function
  4. import sys
  5. import os.path
  6. import json
  7. import jsonpointer
  8. import argparse
  9. parser = argparse.ArgumentParser(
  10. description='Resolve a JSON pointer on JSON files')
  11. # Accept pointer as argument or as file
  12. ptr_group = parser.add_mutually_exclusive_group(required=True)
  13. ptr_group.add_argument('-f', '--pointer-file', type=argparse.FileType('r'),
  14. nargs='?',
  15. help='File containing a JSON pointer expression')
  16. ptr_group.add_argument('POINTER', type=str, nargs='?',
  17. help='A JSON pointer expression')
  18. parser.add_argument('FILE', type=argparse.FileType('r'), nargs='+',
  19. help='Files for which the pointer should be resolved')
  20. parser.add_argument('--indent', type=int, default=None,
  21. help='Indent output by n spaces')
  22. parser.add_argument('-v', '--version', action='version',
  23. version='%(prog)s ' + jsonpointer.__version__)
  24. def main():
  25. try:
  26. resolve_files()
  27. except KeyboardInterrupt:
  28. sys.exit(1)
  29. def parse_pointer(args):
  30. if args.POINTER:
  31. ptr = args.POINTER
  32. elif args.pointer_file:
  33. ptr = args.pointer_file.read().strip()
  34. else:
  35. parser.print_usage()
  36. sys.exit(1)
  37. return ptr
  38. def resolve_files():
  39. """ Resolve a JSON pointer on JSON files """
  40. args = parser.parse_args()
  41. ptr = parse_pointer(args)
  42. for f in args.FILE:
  43. doc = json.load(f)
  44. try:
  45. result = jsonpointer.resolve_pointer(doc, ptr)
  46. print(json.dumps(result, indent=args.indent))
  47. except jsonpointer.JsonPointerException as e:
  48. print('Could not resolve pointer: %s' % str(e), file=sys.stderr)
  49. if __name__ == "__main__":
  50. main()