13

Given a file with a large JSON object all on one line like

{"versions":[{"count":2,"version":""},{"count":1,"version":"1.1.1"},{"count":14,"version":"2.9"},{...

How can I format this to be human readable in Vim?

17

Or you can install jq which is faster (written in C) from your package manager or from source and then in vim, type :

:%!jq .
13

This one-liner works well to format JSON in Vim into a human readable form:

:%!python -m json.tool

1

If PHP is available, add the tool jf as a JSON Formatter by Composer:

$ composer global require codegear/json-formatter

Then Format current file:

:%!jf %

Or add a keymap in vimrc:

nnoremap <Leader>jf :%!jf %<CR>
0

To format in a deterministic way, we need to sort the hash. None of the other answers did that for me, so I created my own:

function! FormatJson()
python << EOF
import vim
import json
try:
    buf = vim.current.buffer
    json_content = '\n'.join(buf[:])
    content = json.loads(json_content)
    sorted_content = json.dumps(content, indent=4, sort_keys=True)
    buf[:] = sorted_content.split('\n')
except Exception, e:
    print e
EOF
endfunction

Usage:

:call FormatJson()
New contributor
Prajit Patil is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
  • Welcome to Vi and Vim! Nice first answer; it's interesting that you consider the sorting aspect! – D. Ben Knoble yesterday
  • About the sorting I'm pretty sure jq mentionned in SebMa answers has a --sort-keys option which would do the job. But it's cool to write your own implementation too :) – statox yesterday

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.