Home>
I want to format json using jq in vim

Current,vim-lsp-settingsI am managing LSP using.
LspDocumentFormatI want to run jq with, so~/.vimrcI wrote in.

augroup jsonSettings
    autocmd!
    autocmd BufNewFile, BufRead * .json setlocal equalprg = jq \ -M \ "."
    autocmd BufWritePre * .json LspDocumentFormat
augroup END

In this statetest.jsonOpen with vim: wWill not format even if you do.

If i make a similar description in Python, it will be formatted.

augroup pythonSettings
    autocmd!
    autocmd BufNewFile, BufRead * .py setlocal colorcolumn = 88 tabstop = 4 softtabstop = 4 shiftwidth = 4 equalprg = yapf \ 2>/dev/null
    autocmd BufWritePre * .py LspDocumentFormat
augroup END

: LspDocumentFormatThen

Document formatting not supported for json

Is output, but how do you think it will work?

Thanks for your professor.

  • Answer # 1

    jq itself is a simple CLI program and has nothing to do with lsp, so it seems that the expected behavior is not achieved even with the description settings.

    This is miso, but I made the following settings with my own plug-in. (Use a tool called efm-langserver to handle the input and output of cli programs well with lsp)

    I think that if you set the same setting to the efm-lang server that you put in vim-lsp-setting, it will work as expected.

    jq-format:&jq-format
        format-command:'jq.'
        format-stdin: true


    https://github.com/tsuyoshicho/vim-efm-langserver-settings/blob/f5a500fc192118e1d42d53cb503af70f62854fd2/config/efm-langserver/config.yaml#L158-L160

    json:
        -<<: * jq-format


    https://github.com/tsuyoshicho/vim-efm-langserver-settings/blob/f5a500fc192118e1d42d53cb503af70f62854fd2/config/efm-langserver/config.yaml#L304-L306