In this post, I want to share how you can work effectively with JSON file inside Neovim.
Format JSON file#
Use Python json module#
If you have Python installed, you can use the following command to format JSON file:
:%!python -m json.tool
Use jq#
Otherwise, we need to install jq
for this:
brew install jq
Then open the JSON file and run the following command:
:%!jq .
In the above command, %
means the whole file, !{some-command}
will run the text in the external some-command
and write the output back to replace the original text. See also :help :range!
inside neovim.
Define a command for this#
We can also define a command to format JSON file:
command! -range JSONFormat <line1>,<line2>!python -m json.tool
Then you can call %JSONFormat
to format the JSON file.
Fold JSON file#
Use the syntax fold#
We can fold JSON file with the old syntax way:
set filetype=json
syntax on
set foldmethod=syntax
Use nvim-treesitter#
If you are using nvim and nvim-treesitter. You can also use treesitter to fold JSON files.
Config for nvim-treesitter:
require("nvim-treesitter.configs").setup {
ensure_installed = { "python", "cpp", "lua", "vim", "json" },
ignore_install = {}, -- List of parsers to ignore installing
highlight = {
enable = true, -- false will disable the whole extension
disable = { 'help' }, -- list of language that will be disabled
},
}
Make sure that JSON parser for treesitter is installed.
Then create after/ftplugin/json.vim
with following config:
set foldmethod=expr
set foldexpr=nvim_treesitter#foldexpr()
Open a valid JSON file, you should be able to see the files are folded properly.
References#
- use external commands to modify text in vim: https://vi.stackexchange.com/a/7189/15292
- format JSON in vim: https://vi.stackexchange.com/q/16906/15292
- vim JSON format: https://salferrarello.com/vim-json-format/
- treesitter JSON fold setup: https://github.com/nvim-treesitter/nvim-treesitter/issues/1337#issuecomment-864205387
- how to fold text in JSON: https://vi.stackexchange.com/q/10562/15292