JSON Validation in BBEdit

I was hand-editing some JSON today in BBEdit, and wanted to keep it valid and nicely formatted. Copying the text and pasting it into jsonlint.com is no fun, so I went looking for a solution.

I found this post on a creating a Python script and dropping it into the right place to get JSON validation. It almost worked, but I had to make two minor changes. One for BBEdit 10 compatibility, and one to get actual line numbers when there's a failure validating.

BBEdit 10 moved where text filters live, so instead of dropping the script into [cci]~/Library/Application Support/BBEdit/Unix Filters[/cci], it needs to go into [cci]~/Library/Application Support/BBEdit/Text Filters[/cci].

The text of the script is:

[cc lang="python"]
#!/usr/local/bin/python
import fileinput
import json
if __name__ == "__main__":
jsonStr = ''
for a_line in fileinput.input():
jsonStr = jsonStr + '\n' + a_line.strip()
jsonObj = json.loads(jsonStr)
print json.dumps(jsonObj, sort_keys=True, indent=2)
[/cc]

The only change I made is replacing the ' ' with '\n' in the line that's appending the string, so the JSON parser is aware of what line number you're on. That way when it fails parsing it can give you a line number, not just a column.