Skip to content

Automatically Format JSON Files in Visual Studio Code

Problem Statement

When working with JSON files in Visual Studio Code, you often encounter files that appear as a single line of dense, unformatted text. Manually formatting these files becomes tedious when you frequently need to press Shift+Alt+F (format document) followed by Ctrl+S (save). This is especially frustrating when the JSON content is regularly updated and reverts to its unformatted state.

Solution: Enable Automatic JSON Formatting

Visual Studio Code provides built-in JSON formatting capabilities that can be configured to automatically format your files.

Keyboard Shortcuts for Manual Formatting

For quick manual formatting, use these keyboard shortcuts:

  • Windows: Shift + Alt + F
  • macOS: Shift + Option + F
  • Linux: Ctrl + Shift + I

Configure Automatic Formatting on Save

To eliminate the need for manual formatting, enable format-on-save:

  1. Open VS Code settings (Ctrl+, or Cmd+, on macOS)
  2. Search for "Format On Save"
  3. Check the box for Editor: Format On Save

Alternatively, add this to your settings.json file:

json
{
  "editor.formatOnSave": true,
  "[json]": {
    "editor.defaultFormatter": "vscode.json-language-features"
  }
}

Check JSON Formatting Settings

WARNING

The JSON > format: Keep Lines setting may prevent proper formatting. If enabled (disabled by default), JSON files with multiple key/values on the same line might not format correctly.

Verify this setting by:

  1. Opening settings (Ctrl+, or Cmd+,)
  2. Searching for "Keep Lines"
  3. Ensure JSON > Format: Keep Lines is unchecked

Or in settings.json:

json
{
  "json.format.keepLines": false
}

While VS Code has built-in JSON support, the Prettier - Code formatter extension provides enhanced formatting options:

  1. Install Prettier from the Extensions marketplace
  2. Set it as your default JSON formatter:
json
{
  "[json]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  }
}

Automatic Formatting Configuration

For the most seamless experience, use this comprehensive configuration:

json
{
  "editor.formatOnSave": true,
  "editor.formatOnPaste": false,
  "editor.formatOnType": false,
  "[json]": {
    "editor.defaultFormatter": "vscode.json-language-features",
    "editor.tabSize": 2
  },
  "json.format.keepLines": false
}

Troubleshooting

If automatic formatting isn't working:

  1. Verify you have a JSON formatter installed
  2. Check that format-on-save is enabled
  3. Ensure the Keep Lines setting is disabled
  4. Restart VS Code if changes don't take effect immediately

By configuring these settings, you'll no longer need to manually format JSON files, saving time and improving your development workflow.