Need help with your JSON?

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

Creating VS Code Extensions for JSON Formatting

If you only need to format JSON in VS Code, the built-in formatter is often enough. Build a custom extension when you need team-specific behavior such as formatting JSON with comments, enforcing project rules, adding commands, or pairing formatting with a dedicated viewer. This guide uses the current VS Code extension workflow as of March 10, 2026, so it reflects today's generator, activation, and publishing flow.

Quick Answer: Do You Need an Extension?

A search for a VS Code JSON formatter often mixes three different jobs. Separate them before you write code:

  • Use VS Code's built-in JSON support if you just want to pretty-print a file with Format Document or format on save.
  • Build a formatter extension if you want JSON or JSONC files to follow custom indentation, newline, or project-specific normalization rules.
  • Build a JSON viewer or custom editor if users need a tree view, form UI, schema-aware editing, or a non-text experience for specific JSON files.

For users who simply want to format JSON in VS Code, start with Format Document, then use Format Document With... if multiple formatters are installed and you need to choose a default.

Pick the Right Extension Shape

A formatter extension and a custom editor solve different problems, and the distinction matters for search intent around "JSON formatter extension VS Code" versus "JSON viewer extension":

  • Formatter provider: Best when the file stays plain text and should respond to Format Document, format-on-save, and default formatter selection.
  • Custom editor: Best when the value is in a tree, inspector, or form-based UI. VS Code exposes this through the customEditors contribution point.
  • Hybrid approach: Many good JSON tools ship both: a formatter for any .json file and a custom editor only for narrow filename patterns where a viewer adds real value.

If you are building a JSON viewer, avoid claiming every *.json file by default. It is usually better to target specific files or keep the custom editor optional so users can still reopen the file in the normal text editor.

Setting up Your Development Environment

The current official starting point is still the VS Code Yeoman generator:

  1. Install a current Node.js release and Git.
  2. Scaffold the project without installing Yeoman globally:
    npx --package yo --package generator-code -- yo code
  3. Choose New Extension (TypeScript). If you know you will depend on modern ESM-only packages, choosing a bundled template usually makes life easier.
  4. Give the extension a clear name such as json-tools or json-formatter-pro.
  5. Open the generated folder in VS Code and press F5 later to launch an Extension Development Host.

The generated project includes the extension manifest, TypeScript entry point, debug launch config, and test scaffolding. That gets you to a working formatter much faster than building the manifest from scratch.

package.json: What Matters and What to Skip

The biggest mistake in older tutorials is inventing a contributes.formatters block. That is not how VS Code formatter extensions are registered. Your formatter is discovered when your extension activates and calls registerDocumentFormattingEditProvider(...).

`package.json` (Relevant Excerpt)

{ "categories": ["Formatters"], "activationEvents": [ "onLanguage:json", "onLanguage:jsonc" ], "main": "./dist/extension.js", "contributes": { "commands": [ { "command": "jsonTools.formatActiveDocument", "title": "JSON Tools: Format Active Document" } ], "configuration": { "title": "JSON Tools", "properties": { "jsonTools.insertFinalNewline": { "type": "boolean", "default": true, "description": "Insert a trailing newline after formatting." } } } } }

A small JSON formatter usually activates on json and jsonc so the provider is ready as soon as those files open. If you add a custom editor later, that lives under contributes.customEditors, not in the formatter registration path.

Implement a Formatter That Handles JSONC

Many JSON files opened in VS Code are actually JSON with comments. A raw JSON.parse plus JSON.stringify approach breaks on comments, trailing commas, and other JSONC cases. A better baseline is jsonc-parser, which Microsoft lists among useful extension modules and which exposes a format API that returns precise text edits.

  1. Install the dependency:
    npm install jsonc-parser
  2. Register a DocumentFormattingEditProvider for both json and jsonc.
  3. Translate the parser's offset-based edits into VS Code TextEdit instances.
  4. Reuse the normal editor formatting command for any command-palette shortcut you expose.

The example below assumes a modern TypeScript extension setup. If your project is still unbundled CommonJS, confirm any helper library you add is compatible with that runtime shape.

`src/extension.ts`

import * as vscode from "vscode"; import { format } from "jsonc-parser"; function toTextEdits( document: vscode.TextDocument, edits: Array<{ offset: number; length: number; content: string }> ): vscode.TextEdit[] { return edits.map((edit) => vscode.TextEdit.replace( new vscode.Range( document.positionAt(edit.offset), document.positionAt(edit.offset + edit.length) ), edit.content ) ); } class JsonDocumentFormatter implements vscode.DocumentFormattingEditProvider { provideDocumentFormattingEdits( document: vscode.TextDocument, options: vscode.FormattingOptions, _token: vscode.CancellationToken ): vscode.TextEdit[] { const config = vscode.workspace.getConfiguration("jsonTools", document.uri); const insertFinalNewline = config.get<boolean>("insertFinalNewline", true); const edits = format(document.getText(), undefined, { insertSpaces: options.insertSpaces, tabSize: options.tabSize, eol: document.eol === vscode.EndOfLine.LF ? "\n" : "\r\n", finalNewline: insertFinalNewline, keepLines: false, }); return toTextEdits(document, edits); } } export function activate(context: vscode.ExtensionContext) { const selector: vscode.DocumentSelector = [{ language: "json" }, { language: "jsonc" }]; context.subscriptions.push( vscode.languages.registerDocumentFormattingEditProvider(selector, new JsonDocumentFormatter()), vscode.commands.registerCommand("jsonTools.formatActiveDocument", async () => { await vscode.commands.executeCommand("editor.action.formatDocument"); }) ); }

This is better than replacing the entire document with one giant edit. VS Code's language feature docs recommend returning the smallest possible edits so diagnostics, markers, and selections stay stable.

Add Rules Without Breaking Real JSON Files

Configuration is where a JSON formatter extension becomes useful instead of redundant. Keep the first version small and predictable:

  • Indentation and end-of-line handling should usually follow VS Code's formatting options.
  • Final newline insertion is a safe project-level toggle and easy to expose through contributes.configuration.
  • Key sorting is useful, but treat it as an advanced opt-in rule. It is straightforward for strict JSON and much trickier if you need to preserve comments and formatting in JSONC files.

Testing and Debugging

VS Code's Extension Development Host is still the fastest way to verify a JSON formatter extension:

  1. Open your extension project folder in VS Code.
  2. Press F5 or start the generated Run Extension launch config.
  3. In the new window, open both a strict .json file and a jsonc file such as a settings file.
  4. Run Format Document With... the first time so you can verify your formatter is actually selected.

Check these cases before you publish:

  • Comments and trailing commas in JSONC inputs.
  • Mixed line endings and final newline behavior.
  • Large files, where full-document rewrites feel sluggish.
  • Conflicts with other installed formatters, especially if users already rely on Prettier or language packs.

Publishing Your Extension

The current Marketplace CLI package is @vscode/vsce. A compact publish flow looks like this:

  1. Install the publishing tool:
    npm install -g @vscode/vsce
  2. Create a Marketplace publisher if you do not already have one, then authenticate:
    vsce login <publisher-id>
  3. Package the extension:
    vsce package
  4. Publish it:
    vsce publish

The most common publishing failure is authentication. The current docs still require an Azure DevOps Personal Access Token with Marketplace manage scope, and the token should usually be created for All accessible organizations.

Troubleshooting and Best Practices

  • The formatter never appears: Check the file's language mode and confirm your activationEvents include onLanguage:json and onLanguage:jsonc.
  • JSONC files break: Avoid raw JSON.parse if you expect comments or trailing commas. That is exactly where a JSON-specific extension should be better than a generic snippet.
  • Diagnostics jump after formatting: Prefer minimal edit sets over replacing the entire document. This keeps markers stable and feels more native.
  • Viewer features start taking over: If you add a JSON tree viewer later, keep it optional or narrow its filename selector so users do not lose normal text editing for every JSON file.
  • Publishing fails with 401/403: Re-check PAT scope and organization selection before debugging anything else.
  • README quality matters: Show one before/after example, explain JSON versus JSONC support, and document how to set your extension as the default formatter for JSON files.

Further Exploration

The official docs worth keeping open while you build are:

Conclusion

A good VS Code JSON formatter extension is usually small: activate only for JSON languages, return precise edits, support JSONC from day one, and avoid turning a formatter into an overbearing custom editor. If you keep those boundaries clear, your extension will serve both users searching for a JSON formatter and teams who need stricter project-specific behavior.

Need help with your JSON?

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