Skip to content

Instantly share code, notes, and snippets.

@markwatson markwatson/pretty_json.py
Last active Dec 12, 2015

Embed
What would you like to do?
A sublime text plugin that pretty formats all the select JSON blobs.
import sublime, sublime_plugin
import json
import re
class PrettyJsonCommand(sublime_plugin.TextCommand):
def run(self, edit):
re_json_p = re.compile(r'^\s*(\w+)\s*\(\s*(.*)\s*\)\s*$')
try:
for region in self.view.sel():
if not region.empty():
# Get the selected text
s = self.view.substr(region)
# Strip out JSONP
func = None
m = re_json_p.match(s)
if m:
func = m.group(1)
s = m.group(2)
# Transform it
s = json.dumps(json.loads(s), sort_keys=True, indent=4)
# Add back the JSONP
if func is not None:
s = func + '(' + s + ')'
# Replace the selection with transformed text
self.view.replace(edit, region, s)
except Exception, e:
sublime.error_message("Error making JSON pretty: " + str(e))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.