I've got, in this case, a Perl module which has some JSON snippets inside of it. I'd like to be able to select the embedded JSON and format it via jq. So far I've got:

:vnoremap jq <esc>:'<,'>:w !jq<CR>

That allows me to select some text, type jq and then the formatted text is displayed to me. However, it's not replacing the selected text. Nothing actually changes in my buffer. What am I missing here? I've seen lots of answers for how to format an entire file, but I can't find a workable answer for this particular use case.

  • 2
    Check :h 'formatprg'
    – user25807
    Commented Jul 16, 2020 at 12:54
  • 2
    What am I missing here? Remove w. (In fact, just :!jq<CR> is enough, the rest is a garbage).
    – Matt
    Commented Jul 16, 2020 at 13:35
  • @Matt if I run that command I just get jq's help menu inserted into my file.
    – oalders
    Commented Jul 16, 2020 at 16:03
  • Thanks. I didn't know about formatprg. That's very handy. If I try :set formatprg=jq and then select the text and enter gq, the JSON is replaced with the help text from jq. I guess it's an issue with how jq is being invoked.
    – oalders
    Commented Jul 16, 2020 at 16:11
  • 2
    vnoremap jq :!jq<cr> works for me.
    – Ralf
    Commented Jul 16, 2020 at 16:28

2 Answers 2


There at least two possible answers here:

vnoremap jq :!jq<cr>

as suggested by @Ralf works for jq >= 1.6. See https://github.com/stedolan/jq/commit/5fe053671a768d28bc9773719cc4a9a35e72f30d

For earlier jq versions where the dot is not implied, it needs to be in the command:

vnoremap jq :!jq .<cr>

I was using an older version of jq. The answer which adds the dot will work with both versions.

If you'd like your keys to be sorted:

vnoremap jq :!jq -S .<cr>
  • 1
    The formatprg version would be set formatprg=jq\ . or let &formatprg = 'jq .'
    – D. Ben Knoble
    Commented Jul 16, 2020 at 23:37

This command will format and sort the json file

:%!jq -S .
  • Welcome to Vi and Vim!
    – D. Ben Knoble
    Commented Mar 20, 2021 at 13:47
  • Note that this doesn't answer the question: OP wants to format snippets of JSON inside a file containing also other code. With % you are sending all the lines to jq so this is likely to insert an error message in your buffer since jq doesn't handle text which is not json.
    – statox
    Commented Mar 24, 2021 at 13:17

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.