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.

54 lines
1.7 KiB

4 years ago
  1. #!/home/alpcentaur/ProjektA/PrototypeWebApp/venv/bin/python3.5
  2. import sys
  3. import json
  4. import argparse
  5. from pprint import pformat
  6. import jmespath
  7. from jmespath import exceptions
  8. def main():
  9. parser = argparse.ArgumentParser()
  10. parser.add_argument('expression')
  11. parser.add_argument('-f', '--filename',
  12. help=('The filename containing the input data. '
  13. 'If a filename is not given then data is '
  14. 'read from stdin.'))
  15. parser.add_argument('--ast', action='store_true',
  16. help=('Pretty print the AST, do not search the data.'))
  17. args = parser.parse_args()
  18. expression = args.expression
  19. if args.ast:
  20. # Only print the AST
  21. expression = jmespath.compile(args.expression)
  22. sys.stdout.write(pformat(expression.parsed))
  23. sys.stdout.write('\n')
  24. return 0
  25. if args.filename:
  26. with open(args.filename, 'r') as f:
  27. data = json.load(f)
  28. else:
  29. data = sys.stdin.read()
  30. data = json.loads(data)
  31. try:
  32. sys.stdout.write(json.dumps(
  33. jmespath.search(expression, data), indent=4))
  34. sys.stdout.write('\n')
  35. except exceptions.ArityError as e:
  36. sys.stderr.write("invalid-arity: %s\n" % e)
  37. return 1
  38. except exceptions.JMESPathTypeError as e:
  39. sys.stderr.write("invalid-type: %s\n" % e)
  40. return 1
  41. except exceptions.UnknownFunctionError as e:
  42. sys.stderr.write("unknown-function: %s\n" % e)
  43. return 1
  44. except exceptions.ParseError as e:
  45. sys.stderr.write("syntax-error: %s\n" % e)
  46. return 1
  47. if __name__ == '__main__':
  48. sys.exit(main())