0

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.

6
  • 2
    Check :h 'formatprg' – Jorengarenar Jul 16 '20 at 12:54
  • 2
    What am I missing here? Remove w. (In fact, just :!jq<CR> is enough, the rest is a garbage). – Matt Jul 16 '20 at 13:35
  • @Matt if I run that command I just get jq's help menu inserted into my file. – oalders Jul 16 '20 at 16:03
  • Thanks @Jorengarenar. 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 Jul 16 '20 at 16:11
  • 2
    vnoremap jq :!jq<cr> works for me. – Ralf Jul 16 '20 at 16:28
1

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
  • 1
    The formatprg version would be set formatprg=jq\ . or let &formatprg = 'jq .' – D. Ben Knoble Jul 16 '20 at 23:37
-1

This command will format and sort the json file

:%!jq -S .
2
  • Welcome to Vi and Vim! – D. Ben Knoble Mar 20 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 Mar 24 at 13:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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