/Lib/json/tool.py

http://unladen-swallow.googlecode.com/ · Python · 37 lines · 33 code · 0 blank · 4 comment · 0 complexity · 7452d9e1f25ae5ff7dddac85808b83b1 MD5 · raw file

  1. r"""Command-line tool to validate and pretty-print JSON
  2. Usage::
  3. $ echo '{"json":"obj"}' | python -mjson.tool
  4. {
  5. "json": "obj"
  6. }
  7. $ echo '{ 1.2:3.4}' | python -mjson.tool
  8. Expecting property name: line 1 column 2 (char 2)
  9. """
  10. import sys
  11. import json
  12. def main():
  13. if len(sys.argv) == 1:
  14. infile = sys.stdin
  15. outfile = sys.stdout
  16. elif len(sys.argv) == 2:
  17. infile = open(sys.argv[1], 'rb')
  18. outfile = sys.stdout
  19. elif len(sys.argv) == 3:
  20. infile = open(sys.argv[1], 'rb')
  21. outfile = open(sys.argv[2], 'wb')
  22. else:
  23. raise SystemExit("{0} [infile [outfile]]".format(sys.argv[0]))
  24. try:
  25. obj = json.load(infile)
  26. except ValueError, e:
  27. raise SystemExit(e)
  28. json.dump(obj, outfile, sort_keys=True, indent=4)
  29. outfile.write('\n')
  30. if __name__ == '__main__':
  31. main()