Skip to content

Instantly share code, notes, and snippets.

@leepro
Created February 28, 2014 18:20
Show Gist options
  • Save leepro/9276645 to your computer and use it in GitHub Desktop.
Save leepro/9276645 to your computer and use it in GitHub Desktop.
Sublime Text 2 script for Prettifying JSON
import sublime, sublime_plugin, json, traceback, sys, re
class PrettifyJsonCommand(sublime_plugin.TextCommand):
def run(self, edit):
# Get the current selection
if self.view.sel()[0].empty():
region = sublime.Region(0L, self.view.size())
source = self.view.substr(region).encode('utf-8')
else:
region = self.view.sel()[0]
source = self.view.substr(self.view.sel()[0]).encode('utf-8')
#print source
try:
result = json.loads(source)
result = json.dumps(result, sort_keys=True, indent=2)
# Replace the buffer
self.view.replace(edit, region, result.decode('utf-8'))
except ValueError, err:
err = str(err)
linecol = re.compile(r' line (\d+) column (\d+) ')
ret = linecol.search(err)
if ret!=None:
err = "# Error:"+str(ret.groups())+"\n"
row, col = [ int(g) for g in ret.groups() ]
lines = source.split('\n')
idx = len("\n".join(lines[:row-1]))
target_region = sublime.Region(idx, idx+col)
self.view.sel().clear()
self.view.sel().add(target_region)
else:
err = "# Unknown Error:"+err+"\n"
result = err+source
def description(self):
return "Prettify Json"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment