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

How do I format and pretty-print JSON in the current Vim buffer using Python?

Answer

:%!python -m json.tool

Explanation

When editing JSON files in Vim, you can pipe the entire buffer through Python's built-in json.tool module to reformat it with consistent indentation and sorted keys. The %! prefix means "filter the entire file through the following shell command and replace the buffer contents with the output."

How it works

  • % — address representing the entire file (all lines)
  • ! — filter operator: pipe the addressed lines through a shell command
  • python -m json.tool — Python's JSON pretty-printer, reads from stdin and writes formatted JSON to stdout

Example

Given a minified JSON buffer:

{"name":"Alice","age":30,"city":"London"}

After running :%!python -m json.tool:

{
    "age": 30,
    "city": "London",
    "name": "Alice"
}

Note: json.tool sorts keys alphabetically by default.

Tips

  • Use python3 explicitly if needed: :%!python3 -m json.tool
  • Disable key sorting (Python 3.7+): :%!python3 -m json.tool --no-sort-keys
  • Set indent width (Python 3.2+): :%!python3 -m json.tool --indent 2
  • For faster formatting, substitute jq '.' if jq is installed: :%!jq '.'
  • If Python is unavailable, :%!jq . achieves the same result with jq
  • If the JSON is invalid, the command will fail and Vim will report the parse error

Next

How do I open the directory containing the current file in netrw from within Vim?