tool.py 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. r"""
  2. Using simplejson from the shell to validate and
  3. pretty-print::
  4. $ echo '{"json":"obj"}' | python -msimplejson
  5. {
  6. "json": "obj"
  7. }
  8. $ echo '{ 1.2:3.4}' | python -msimplejson
  9. Expecting property name: line 1 column 2 (char 2)
  10. Note that the JSON produced by this module's default settings
  11. is a subset of YAML, so it may be used as a serializer for that as well.
  12. """
  13. import simplejson
  14. #
  15. # Pretty printer:
  16. # curl http://mochikit.com/examples/ajax_tables/domains.json | python -msimplejson.tool
  17. #
  18. def main():
  19. import sys
  20. if len(sys.argv) == 1:
  21. infile = sys.stdin
  22. outfile = sys.stdout
  23. elif len(sys.argv) == 2:
  24. infile = open(sys.argv[1], 'rb')
  25. outfile = sys.stdout
  26. elif len(sys.argv) == 3:
  27. infile = open(sys.argv[1], 'rb')
  28. outfile = open(sys.argv[2], 'wb')
  29. else:
  30. raise SystemExit("%s [infile [outfile]]" % (sys.argv[0],))
  31. try:
  32. obj = simplejson.load(infile)
  33. except ValueError, e:
  34. raise SystemExit(e)
  35. simplejson.dump(obj, outfile, sort_keys=True, indent=4)
  36. outfile.write('\n')
  37. if __name__ == '__main__':
  38. main()