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.
gg=G
is what you need if you are using vim.Here's an example in Ruby:
(https://gist.github.com/zinovyev/c4b6ec3c24670278adfebfb9ecced84b)
Easier way is to just external command as a filter for a selection. e.g.
:!python -m json.tool
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:Just run
:JsonTool
and it will pretty print the current line. It can take a range as well: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
andij
as well as print print JSON formatting, e.g.gqaj
.If you have
jq
(source) available, you can use in the command mode: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: