Last active
December 30, 2015 22:39
-
-
Save rgl/7895875 to your computer and use it in GitHub Desktop.
this is a sublime text 3 plugin to format selected (or all file) JSON text.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# | |
# Copy this file into the user package directory (eg. to C:\Users\Rui Lopes\AppData\Roaming\Sublime Text 3\Packages\User). | |
# NB you can go into this directory by opening the Preferences | Browse Packages... menu. | |
# | |
# Add a shortcut to run this command by using sublime Preferences | Key Bindings - User: | |
# | |
# [ | |
# { | |
# "keys": ["ctrl+shift+j"], | |
# "command": "format_json" | |
# } | |
# ] | |
# | |
# | |
# Also, create a file named Main.sublime-menu (eg. at C:\Users\rgl\AppData\Roaming\Sublime Text 2\Packages\User\) to | |
# add this command to Selection menu: | |
# | |
# [ | |
# { | |
# "id": "selection", | |
# "caption": "Selection", | |
# "children": [ | |
# { | |
# "id": "format", | |
# "caption": "Format", | |
# "children": [ | |
# { | |
# "caption": "Format JSON", | |
# "command": "format_json" | |
# } | |
# ] | |
# } | |
# ] | |
# } | |
# ] | |
# | |
# For a XML formatter see https://gist.github.com/rgl/5884996 | |
import sublime | |
import sublime_plugin | |
import re | |
import json | |
import collections | |
# See http://www.sublimetext.com/docs/3/api_reference.html | |
class FormatJsonCommand(sublime_plugin.TextCommand): | |
def run(self, edit): | |
try: | |
selections = self.view.sel() | |
# if there is no selected text, apply to all text. | |
if len(selections) == 1 and selections[0].empty(): | |
selections = [sublime.Region(0, self.view.size())] | |
for sel in selections: | |
text = self.view.substr(sel) | |
obj = json.loads(text, object_pairs_hook=collections.OrderedDict) | |
formatted_json = json.dumps(obj, sort_keys=False, indent=4, separators=(',', ': ')) | |
self.view.replace(edit, sel, formatted_json) | |
except Exception as e: | |
sublime.error_message(u"ERROR formating JSON: %s" % e) | |
def clear(self): | |
self.view.erase_status('tidy_json') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment