tool.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. r"""Command-line tool to validate and pretty-print JSON
  2. Usage::
  3. $ echo '{"json":"obj"}' | python -m json.tool
  4. {
  5. "json": "obj"
  6. }
  7. $ echo '{ 1.2:3.4}' | python -m json.tool
  8. Expecting property name enclosed in double quotes: line 1 column 3 (char 2)
  9. """
  10. import argparse
  11. import json
  12. import sys
  13. def main():
  14. prog = 'python -m json.tool'
  15. description = ('A simple command line interface for json module '
  16. 'to validate and pretty-print JSON objects.')
  17. parser = argparse.ArgumentParser(prog=prog, description=description)
  18. parser.add_argument('infile', nargs='?', type=argparse.FileType(encoding="utf-8"),
  19. help='a JSON file to be validated or pretty-printed')
  20. parser.add_argument('outfile', nargs='?', type=argparse.FileType('w', encoding="utf-8"),
  21. help='write the output of infile to outfile')
  22. parser.add_argument('--sort-keys', action='store_true', default=False,
  23. help='sort the output of dictionaries alphabetically by key')
  24. options = parser.parse_args()
  25. infile = options.infile or sys.stdin
  26. outfile = options.outfile or sys.stdout
  27. sort_keys = options.sort_keys
  28. with infile:
  29. try:
  30. obj = json.load(infile)
  31. except ValueError as e:
  32. raise SystemExit(e)
  33. with outfile:
  34. json.dump(obj, outfile, sort_keys=sort_keys, indent=4)
  35. outfile.write('\n')
  36. if __name__ == '__main__':
  37. main()