How to fix JSON indentation in vim?

2020-02-23 05:36发布

In vim, the default indentation for JSON is:

{
    "employees": [
    { "firstName":"John" , "lastName":"Doe" }, 
    { "firstName":"Anna" , "lastName":"Smith" }, 
    { "firstName":"Peter" , "lastName":"Jones" }
    ]
}

But what I expect is:

{
    "employees": [
        { "firstName":"John" , "lastName":"Doe" }, 
        { "firstName":"Anna" , "lastName":"Smith" }, 
        { "firstName":"Peter" , "lastName":"Jones" }
    ]
}

I did google and tried some vim-json plugins, but none of them fix this issue.

7条回答
▲ chillily
2楼-- · 2020-02-23 06:12

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

查看更多
登录 后发表回答