In vim, the default indentation for JSON is:
{
\"employees\": [
{ \"firstName\":\"John\" , \"lastName\":\"Doe\" },
{ \"firstName\":\"Anna\" , \"
Here's an example in Ruby:
:%! ruby -rjson -e "print JSON.pretty_generate(JSON.parse(ARGF.read))"
(https://gist.github.com/zinovyev/c4b6ec3c24670278adfebfb9ecced84b)
gg=G
is what you need if you are using vim.
If you have jq
(source) available, you can use in the command mode:
:%!jq .
You can send to an external tool, as an example, if you have python you can send the content to python's json tool using:
:%!python -m json.tool
python -m json.tool
reorders the position of the JSON object properties, if you have node installed, you can just use this function:
function FormatJSON(...)
let code="\"
\ var i = process.stdin, d = '';
\ i.resume();
\ i.setEncoding('utf8');
\ i.on('data', function(data) { d += data; });
\ i.on('end', function() {
\ console.log(JSON.stringify(JSON.parse(d), null,
\ " . (a:0 ? a:1 ? a:1 : 2 : 2) . "));
\ });\""
execute "%! node -e " . code
endfunction
Mapped to f-j
in .vimrc
nmap fj :<C-U>call FormatJSON(v:count)<CR>
You can also pass a number of spaces for a tab, 2 are the default if you don't specify any.
4fj
My complete .vimrc is here https://github.com/botverse/.dotfiles/blob/master/.vimrc
romainl recommendation is the preferred way, but sometimes you need to pretty indent JSON text inside some buffer that doesn't have the json
filetype. I use this nice command:
command! -range -nargs=0 -bar JsonTool <line1>,<line2>!python -m json.tool
Just run :JsonTool
and it will pretty print the current line. It can take a range as well:
:JsonTool
:'<,'>JsonTool
:10,25JsonTool
If you do not have python or prefer a pure vim solution you may be interested in Tim Pope's jdaddy plugin. Jdaddy provides JSON text objects: aj
and ij
as well as print print JSON formatting, e.g. gqaj
.