#!/usr/bin/env python
import sys
import os
import json

if len(sys.argv) == 2 and sys.argv[1] == '--help':
    print """
Usage: cleanjson.py [input_file] [output_file]

  If input_file is not provided, input will be read from stdin and delivered to
  stdout.

  If output_file is not provided, output will be delivered to stdout. You
  cannot set output_file unless input_file was also set.

Examples:

  Clean json from input.json and write to output.json:

      cleanjson.py input.json output.json

  Clean json from stdin and write to stdout:

      cleanjson.py <input.json

  Clean json from stdin and write to stdout (file):

      cleanjson.py <input.json >output.json

  You can also use cleanjson.py as a pipe:

      cat input.json | cleanjson.py >output.json
"""
    sys.exit(0)

json_obj = None

# if any args are given (other than --help, handled above), the first is the
# input filename. Otherwise, input comes from stdin.
if len(sys.argv) > 1:
    json_file_name = sys.argv[1]
    if not os.path.exists(json_file_name):
        print "Invalid file path: %s" % json_file_name
        sys.exit(1)
    f = open(json_file_name, 'r')
    json_obj = json.load(f)
    f.close()
else:
    json_obj = json.load(sys.stdin)

# convert the read-in object back into json. This prettifies it.
json_text = json.dumps(json_obj, indent=2)

# if more than one arg is given, the second arg is the output filename.
# Otherwise, output goes to stdout.
if len(sys.argv) > 2:
    json_file_name = sys.argv[2]
    f = open(json_file_name, 'w')
    f.write("%s\n" % json_text)
    f.close()
else:
    sys.stdout.write("%s\n" % json_text)
