tool.py 1.1 KB

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