0

Work with JSON File in Neovim

 11 months ago
source link: https://jdhao.github.io/2023/06/12/neovim-json-file/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Work with JSON File in Neovim

2023-06-12291 words 2 mins read 16 times read

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

Author jdhao

LastMod 2023-06-12

License CC BY-NC-ND 4.0

Prev Next


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK