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.
JSON is a serialization format, not a presentation format. As such, there is no "standard" indentation - JSON is typically sent as compactly as possible.
The indent parameter specifies the spaces that are used at the beginning of a line. We can use the indent parameter of json. dump() to specify the indentation value. By default, when you write JSON data into a file, Python doesn't use indentations and writes all data on a single line, which is not readable.
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:
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.
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
If you have jq (source) available, you can use in the command mode:
:%!jq .
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With