Paul Calnan
Published August 11, 2012

I got the idea for this script from a BBEdit script I found on Tumblr. I posted it to my Tumblr site as well. The script simply reformats and cleans up JSON files.

Since then, I have revisited and changed the script. Originally, the script used a fileinput object to build an input string, which it passed to the JSON parser. It also didn't do much in the way of error handling.

I updated it to pass stdin directly to the JSON parser. It now catches exceptions thrown while parsing.

The new code looks like this:

#!/usr/bin/env python

from __future__ import print_function
import sys
import json

def main():
        obj = json.load(sys.stdin)
        json.dump(obj, sys.stdout, sort_keys=True, indent=4)
    except ValueError as strerr:
        print("Error: {0}".format(strerr), file=sys.stderr)

if __name__ == "__main__":