In this post, I want to share how you can work effectively with JSON file inside Neovim.
If you have Python installed, you can use the following command to format JSON file:
:%!python -m json.toolOtherwise, we need to install jq for this:
brew install jqThen 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.
We can also define a command to format JSON file:
command! -range JSONFormat <line1>,<line2>!python -m json.toolThen you can call %JSONFormat to format the JSON file.
We can fold JSON file with the old syntax way:
set filetype=json
syntax on
set foldmethod=syntaxIf 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.
In this post, I want to share how you can work effectively with JSON file inside Neovim.
If you have Python installed, you can use the following command to format JSON file:
:%!python -m json.toolOtherwise, we need to install jq for this:
brew install jqThen 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.
We can also define a command to format JSON file:
command! -range JSONFormat <line1>,<line2>!python -m json.toolThen you can call %JSONFormat to format the JSON file.
We can fold JSON file with the old syntax way:
set filetype=json
syntax on
set foldmethod=syntaxIf 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.