vimtricks.wiki Concise Vim tricks, one at a time.

How do I pretty-print or format JSON directly in Vim?

Answer

:%!python3 -m json.tool

Explanation

The :%! command pipes the entire buffer through an external command and replaces it with the output. Using Python's built-in json.tool module, you can instantly format minified JSON into a readable, indented structure.

How it works

" Format entire buffer as JSON
:%!python3 -m json.tool

" Format only selected lines
:'<,'>!python3 -m json.tool

" Format current line (single-line JSON)
:.!python3 -m json.tool

Before

{"name":"John","age":30,"address":{"city":"NYC","zip":"10001"},"hobbies":["vim","coding"]}

After :%!python3 -m json.tool

{
    "name": "John",
    "age": 30,
    "address": {
        "city": "NYC",
        "zip": "10001"
    },
    "hobbies": [
        "vim",
        "coding"
    ]
}

Alternative tools

" Using jq (faster, more features)
:%!jq .

" Compact (minify) JSON with jq
:%!jq -c .

" Sort keys
:%!python3 -m json.tool --sort-keys
:%!jq -S .

Tips

  • If the JSON is invalid, the command will show an error — this doubles as a JSON validator
  • Use u to undo immediately if the formatting isn't what you expected
  • For XML formatting: :%!xmllint --format -
  • For SQL formatting: :%!sqlformat -r -k upper -
  • The same :%! pattern works with any text-processing tool on your system

Next

How do I always access my last yanked text regardless of deletes?