Need help with your JSON?

Try our JSON Formatter tool to automatically identify and fix syntax errors in your JSON. JSON Formatter tool

Creating Sublime Text Packages for JSON Formatting

Sublime Text is a powerful and highly customizable text editor widely used by developers. One of its greatest strengths lies in its extensive package system, allowing users to extend its functionality with plugins, color schemes, syntax definitions, and more. For developers working frequently with JSON data, having a quick and reliable way to format ugly, unreadable JSON is essential. This guide will walk you through creating your own Sublime Text package specifically for JSON formatting.

We'll explore two main approaches: using an external formatter tool and building a simple Python plugin that leverages Sublime Text's built-in capabilities and Python's standard library.

What is a Sublime Text Package?

A Sublime Text package is essentially a collection of files organized in a specific directory structure that Sublime Text recognizes. These files can include Python scripts (.py) for plugins, JSON files for settings, key bindings, and commands, XML files for syntax definitions, and more. Packages are installed in the "Packages" directory of your Sublime Text installation. They can be installed as loose files (recommended for development) or as compressed `.sublime-package` files (recommended for distribution).

Prerequisites (Corrected: Used Wrench icon)

  • Sublime Text installed (version 3 or 4 recommended).
  • Basic familiarity with JSON structure.
  • For Method 1 (External Formatter): An external JSON formatting tool (like jq, prettier, or even Python'sjson.tool module via the command line) installed and available in your system's PATH.
  • For Method 2 (Python Plugin): Basic understanding of Python (Sublime Text plugins are written in Python).

Package Structure

To start, open Sublime Text and go to Preferences > Browse Packages.... This will open the "Packages" directory in your file explorer. Create a new folder inside this directory for your package. Let's call it JsonFormatter.

Packages/ 
├── User/ (Existing folder for your personal settings)
└── JsonFormatter/ (New folder for your package)
    ├── Default.sublime-commands (Command Palette entries)
    ├── Default.sublime-keymap (Keyboard shortcuts)
    └── ... other package files will go here ...

We'll add more files to the JsonFormatter folder depending on the method we choose.

Method 1: Using an External Formatter

This method is simpler if you already have a preferred command-line JSON formatter. Sublime Text can be configured to send the current buffer's content to an external command and replace the buffer content with the command's output. This is typically done using a "Build System" or directly via a Python plugin that uses the `subprocess` module. We'll use a Build System as it's a common and relatively easy way to achieve this.

Creating a Build System

Inside your JsonFormatter package folder, create a new file named JsonFormatter.sublime-build.

JsonFormatter.sublime-build:

{ 
  "name": "JSON Formatter (External)",
  "cmd": ["python", "-m", "json.tool"],
  "file_regex": "^...(.?):([0-9]+):?([0-9]+)?",
  "selector": "source.json",
  "shell": true,
  "working_dir": "$file_path",
  "input_regex": "",
  "target": "pipe_build",
  "pipe_input": "$contents"
}

Let's break down this JSON file:

  • "name": The name that appears in the Build System menu.
  • "cmd": The command to execute. Here, we use Python's built-in json.tool module. You could replace this with["jq"] or ["prettier", "--parser", "json"]or any other command-line JSON formatter.
  • "selector": This build system will only be available when editing files with the `source.json` syntax (i.e., JSON files).
  • "shell": Set to true if your command needs to run in a shell (e.g., for piping).
  • "target": "pipe_build": This special target allows piping input to the command and replacing the buffer with the output.
  • "pipe_input": "$contents": This tells Sublime Text to pipe the entire content of the current buffer (`$contents`) as input to the command specified in "cmd".
  • "file_regex", "working_dir","input_regex": Standard build system keys; adjusted for piping but less critical for simple formatting.

Adding Command Palette Entry

To make this easily accessible via the Command Palette (Ctrl+Shift+P or Cmd+Shift+P), create a file named Default.sublime-commands in yourJsonFormatter folder.

Default.sublime-commands:

[ 
  {
    "caption": "JsonFormatter: Format JSON (External)",
    "command": "build",
    "args": { "build_system": "Packages/JsonFormatter/JsonFormatter.sublime-build" }
  }
]

Now you can open a JSON file, press Ctrl+Shift+P, type "JsonFormatter", and select "JsonFormatter: Format JSON (External)" to format the current file.

Adding a Keyboard Shortcut

For even faster access, add a keyboard shortcut. Create or edit theDefault.sublime-keymap file in your JsonFormatterfolder.

Default.sublime-keymap:

[ 
  { "keys": ["ctrl+alt+f"], "command": "build", "args": { "build_system": "Packages/JsonFormatter/JsonFormatter.sublime-build" } },
  
]

This example assigns Ctrl+Alt+F (or Cmd+Alt+F on macOS) to run the build system when a key combination is pressed. Choose a key combination that doesn't conflict with existing shortcuts.

To use this method: Open a JSON file, ensure its syntax is set to JSON, and either run the build system manually (Tools > Build System > JSON Formatter (External) then Tools > Build or press F7), use the Command Palette entry, or press your defined keyboard shortcut.

Method 2: Using a Python Plugin

For more control, or if you don't want to rely on external command-line tools, you can write a Python plugin. Sublime Text provides an API that allows plugins to interact with views (editor tabs), selections, settings, and more.

Creating the Plugin File

Inside your JsonFormatter package folder, create a new file named json_formatter_plugin.py.

json_formatter_plugin.py:

import sublime 
import sublime_plugin
import json

class FormatJsonCommand(sublime_plugin.TextCommand):
    """
    Sublime Text Command to format the current view's JSON content.
    """
    def run(self, edit):
        view = self.view
        
         # Get the entire content of the buffer
         region = sublime.Region(0, view.size())
         content = view.substr(region)
        
         try:
             # Parse the JSON content
             data = json.loads(content)
            
             # Format the JSON
             # Use indent=4 for readability, separators=(', ', ': ') for standard formatting
             formatted_json = json.dumps(data, indent=4, separators=(', ', ': '))
            
             # Replace the original content with the formatted JSON
             view.replace(edit, region, formatted_json)
            
             # Optional: show a status message
             sublime.status_message("JSON formatted successfully!")
            
         except json.JSONDecodeError as e:
             # Handle JSON parsing errors
             sublime.error_message(f"JSON Formatting Error: {e}")
         except Exception as e:
             # Handle any other potential errors
             sublime.error_message(f"An unexpected error occurred: {e}")

Explanation of the Python code:

  • import sublime, sublime_plugin, json: Imports the necessary Sublime Text modules and Python's built-in JSON library.
  • class FormatJsonCommand(...): Defines a custom Sublime Text command. The class name implicitly defines the command name (lowercase and underscores): format_json.
  • def run(self, edit):: This is the method Sublime Text calls when the command is executed. The edit object is required for making modifications to the buffer.
  • view = self.view: Gets the current editor view object.
  • region = sublime.Region(0, view.size()): Creates a region that covers the entire buffer content.
  • content = view.substr(region): Reads the text content within the defined region (the whole file).
  • json.loads(content): Parses the string content into a Python dictionary or list.
  • json.dumps(data, indent=4, separators=...): Converts the Python object back into a JSON string, using 4-space indentation and standard separators for pretty-printing.
  • view.replace(edit, region, formatted_json): Replaces the original content (covered by the region) with theformatted_json string. This requires the editobject obtained in the run method.
  • try...except json.JSONDecodeError: Basic error handling to catch invalid JSON input. Sublime Text's error_messageis used to display a popup.
  • sublime.status_message(...): Displays a temporary message in the status bar.

Adding Command Palette Entry (for Plugin)

Edit your Default.sublime-commands file in the JsonFormatter folder to add an entry for the new plugin command.

Default.sublime-commands:

[ 
  {
    "caption": "JsonFormatter: Format JSON (Plugin)",
    "command": "format_json"
  }
  ,
  
  {
    "caption": "JsonFormatter: Format JSON (External)",
    "command": "build",
    "args": { "build_system": "Packages/JsonFormatter/JsonFormatter.sublime-build" }
  }
]

Notice the "command": "format_json" matches the lowercase, underscore version of your Python class name FormatJsonCommand.

Adding a Keyboard Shortcut (for Plugin)

Edit your Default.sublime-keymap file to add a shortcut for the plugin command.

Default.sublime-keymap:

[ 
  { "keys": ["ctrl+alt+j"], "command": "format_json", "context":
    [
      { "key": "selector", "operator": "equal", "operand": "source.json" },
      { "key": "setting.json", "operator": "equal", "operand": true },
    ]
  },
  
  { "keys": ["ctrl+alt+f"], "command": "build", "args": { "build_system": "Packages/JsonFormatter/JsonFormatter.sublime-build" } }
  
]

This example assigns Ctrl+Alt+J (or Cmd+Alt+J) to run the format_json command. We've also added a"context" key to ensure this shortcut only activates when editing a JSON file (`source.json` syntax).

To use this method: Open a JSON file, ensure its syntax is set to JSON, and either use the Command Palette entry ("JsonFormatter: Format JSON (Plugin)") or press your defined keyboard shortcut (e.g., Ctrl+Alt+J). Sublime Text automatically loads and reloads plugin files ending in .py in the Packages directory.

Customization and Settings

For the Python plugin method, you might want to make the indentation level or other json.dumps parameters configurable. You can do this by adding a settings file.

Create a file named JsonFormatter.sublime-settings in yourJsonFormatter folder.

JsonFormatter.sublime-settings:

{ 
  // The number of spaces to use for indentation when formatting JSON
  "json_indent_spaces": 4
}

Then, in your json_formatter_plugin.py, you can read this setting:

Reading settings in json_formatter_plugin.py:

# Inside the run method: 
settings = sublime.load_settings('JsonFormatter.sublime-settings')
indent_spaces = settings.get('json_indent_spaces', 4) # Default to 4 if setting not found

# Then use it in json.dumps:
formatted_json = json.dumps(data, indent=indent_spaces, separators=(', ', ': '))

Users can override this setting by creating a file with the same name in their User package folder (Packages/User/JsonFormatter.sublime-settings).

Installing the Package

If you followed the steps above and placed the files in a new folder (e.g., Packages/JsonFormatter), your package is already "installed" in development mode. Sublime Text automatically picks up changes to .py, .sublime-commands, and .sublime-keymap files. You might need to restart Sublime Text for build systems (`.sublime-build`) to appear in the menu, but the Command Palette and keybindings should work immediately after saving the files.

For distributing your package, you would typically zip the contents of the JsonFormatter folder and rename the zip file toJsonFormatter.sublime-package. Users can then install this by dragging it into the "Installed Packages" directory (Preferences > Browse Packages... and navigate up one level to find "Installed Packages").

Conclusion

Creating Sublime Text packages for JSON formatting is a practical way to automate a common development task and tailor your editor workflow. Whether you prefer leveraging existing external tools via a build system or crafting a custom solution with a Python plugin, Sublime Text's flexible package system provides the necessary tools.

By following the steps outlined above, you've not only created a useful utility but also gained insight into how Sublime Text packages work, which opens the door to further customization and development of more complex tools within your favorite text editor.

Need help with your JSON?

Try our JSON Formatter tool to automatically identify and fix syntax errors in your JSON. JSON Formatter tool