How to Format JSON in TextWrangler [#iosdev, #json, #webdev]

If you’re a TextWrangler user and you wanted to be able to format a block of JSON, you can do it yourself by following the instructions at Java Dev on Mac OS X: Format JSON in TextWrangler

1. Create text (Python) file called “Format JSON” in the following location:

~/Library/Application Support/TextWrangler/Text Filters/Format JSON.py

2. Add the following Python code to take care of the formatting:

#!/usr/local/bin/python
import fileinput
import json
if __name__ == "__main__":
  text = ''
  for line in fileinput.input():
    text = text + ' ' + line.strip()
  jsonObj = json.loads(text)
  print json.dumps(jsonObj, sort_keys=True, indent=2)

One thing that tripped me up is that you need to select a block of text before running the macro. Otherwise it works great.

Thanks for the tip!

UPDATE:
I’m not sure if it was due to installing newer versions of Xcode or Mountain Lion, but I noticed that I was getting an error when attempting to run the script.

Evidently the first line:

#!/usr/local/bin/python

Might need to be:

#!/usr/bin/python

…or maybe you could create a symbolic link as well, but for me, since I’m not a Python guru, modifying the script was the easiest way to fix the problem.