m2m模型翻译
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.

68 lines
2.0 KiB

6 months ago
  1. #!/usr/bin/python
  2. # encoding: utf-8
  3. # Copyright © 2012 Felix Richter <wtfpl@syntax-fehler.de>
  4. # This work is free. You can redistribute it and/or modify it under the
  5. # terms of the Do What The Fuck You Want To Public License, Version 2,
  6. # as published by Sam Hocevar. See the COPYING file for more details.
  7. # Standard Library imports
  8. import json
  9. import sys
  10. import glob
  11. import argparse
  12. # JsonPath-RW imports
  13. from jsonpath_ng import parse
  14. def find_matches_for_file(expr, f):
  15. return expr.find(json.load(f))
  16. def print_matches(matches):
  17. print('\n'.join(['{0}'.format(match.value) for match in matches]))
  18. def main(*argv):
  19. parser = argparse.ArgumentParser(
  20. description='Search JSON files (or stdin) according to a JSONPath expression.',
  21. formatter_class=argparse.RawTextHelpFormatter,
  22. epilog="""
  23. Quick JSONPath reference (see more at https://github.com/kennknowles/python-jsonpath-rw)
  24. atomics:
  25. $ - root object
  26. `this` - current object
  27. operators:
  28. path1.path2 - same as xpath /
  29. path1|path2 - union
  30. path1..path2 - somewhere in between
  31. fields:
  32. fieldname - field with name
  33. * - any field
  34. [_start_?:_end_?] - array slice
  35. [*] - any array index
  36. """)
  37. parser.add_argument('expression', help='A JSONPath expression.')
  38. parser.add_argument('files', metavar='file', nargs='*', help='Files to search (if none, searches stdin)')
  39. args = parser.parse_args(argv[1:])
  40. expr = parse(args.expression)
  41. glob_patterns = args.files
  42. if len(glob_patterns) == 0:
  43. # stdin mode
  44. print_matches(find_matches_for_file(expr, sys.stdin))
  45. else:
  46. # file paths mode
  47. for pattern in glob_patterns:
  48. for filename in glob.glob(pattern):
  49. with open(filename) as f:
  50. print_matches(find_matches_for_file(expr, f))
  51. def entry_point():
  52. main(*sys.argv)