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条回答
相关推荐>>
2楼-- · 2020-02-23 05:52

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

查看更多
再贱就再见
3楼-- · 2020-02-23 05:54

Here's an example in Ruby:

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

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

查看更多
唯我独甜
4楼-- · 2020-02-23 05:56

Easier way is to just external command as a filter for a selection. e.g.

  1. Make a selection
  2. Type :!python -m json.tool
查看更多
劫难
5楼-- · 2020-02-23 06:02

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.

查看更多
Deceive 欺骗
6楼-- · 2020-02-23 06:05

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

:%!jq .
查看更多
劳资没心,怎么记你
7楼-- · 2020-02-23 06:09

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
查看更多
登录 后发表回答