67

I have a large JSON file. It is not easy to work on all file at a time. I want to fold some content so that I can work on a section of JSON file.

E.g.:

{
  obj: {+}, // folded section
  obj:{
        // unfolded section
     }
}

Is it possible to fold JSON structure in Vim?

2 Answers 2

100

Yes, it is possible. A minimal setup would be:

:set filetype=json
:syntax on
:set foldmethod=syntax
6
  • 2
    what keystroke needed to fold and unfold a section?
    – WitVault
    Commented Dec 9, 2016 at 11:04
  • 12
    :h fold-commands - zo - open and zc - close
    – grodzik
    Commented Dec 9, 2016 at 11:46
  • 13
    za - toggle fold
    – alecdwm
    Commented Aug 12, 2019 at 7:26
  • 2
    FWIW: This isn't enabling folding for me. "E490: No fold found".
    – spazm
    Commented Nov 3, 2020 at 20:40
  • 2
    @spazm: So you can probably ask a new question here, describe what OS you're using, what exact editor, what version, all the steps you're doing, all the info that could be helpful.
    – grodzik
    Commented Nov 5, 2020 at 12:53
2

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.

Ref:

https://github.com/nvim-treesitter/nvim-treesitter/issues/1337#issuecomment-864205387

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.