Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fix JSON indentation in vim?

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.

like image 508
user2309998 Avatar asked May 18 '13 04:05

user2309998


People also ask

Is JSON sensitive to indentation?

JSON is a serialization format, not a presentation format. As such, there is no "standard" indentation - JSON is typically sent as compactly as possible.

What is JSON indentation?

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.


4 Answers

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
like image 54
awesome_person Avatar answered Sep 20 '22 23:09

awesome_person


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.

like image 41
Peter Rincker Avatar answered Sep 18 '22 23:09

Peter Rincker


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
like image 41
Reut Sharabani Avatar answered Sep 21 '22 23:09

Reut Sharabani


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

:%!jq .
like image 41
gabra Avatar answered Sep 18 '22 23:09

gabra