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:
- Open VS Code settings (
Ctrl+,orCmd+,on macOS) - Search for "Format On Save"
- Check the box for
Editor: Format On Save
Alternatively, add this to your settings.json file:
{
"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:
- Opening settings (
Ctrl+,orCmd+,) - Searching for "Keep Lines"
- Ensure
JSON > Format: Keep Linesis unchecked
Or in settings.json:
{
"json.format.keepLines": false
}Recommended JSON Extension
While VS Code has built-in JSON support, the Prettier - Code formatter extension provides enhanced formatting options:
- Install Prettier from the Extensions marketplace
- Set it as your default JSON formatter:
{
"[json]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
}
}Automatic Formatting Configuration
For the most seamless experience, use this comprehensive configuration:
{
"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:
- Verify you have a JSON formatter installed
- Check that format-on-save is enabled
- Ensure the
Keep Linessetting is disabled - 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.