How to fix JSON indentation in vim?

前端 未结 8 1286
粉色の甜心
粉色の甜心 2020-12-29 03:55

In vim, the default indentation for JSON is:

{
    \"employees\": [
    { \"firstName\":\"John\" , \"lastName\":\"Doe\" }, 
    { \"firstName\":\"Anna\" , \"         


        
相关标签:
8条回答
  • 2020-12-29 04:12

    Here's an example in Ruby:

    :%! ruby -rjson -e "print JSON.pretty_generate(JSON.parse(ARGF.read))"
    

    (https://gist.github.com/zinovyev/c4b6ec3c24670278adfebfb9ecced84b)

    0 讨论(0)
  • 2020-12-29 04:14

    gg=G is what you need if you are using vim.

    0 讨论(0)
  • 2020-12-29 04:18

    If you have jq (source) available, you can use in the command mode:

    :%!jq .
    
    0 讨论(0)
  • 2020-12-29 04:23

    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
    
    0 讨论(0)
  • 2020-12-29 04:23

    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

    0 讨论(0)
  • 2020-12-29 04:27

    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.

    0 讨论(0)
提交回复
热议问题