xenteros
xenteros

Reputation: 15842

Is there an easy way to reverse pretty print of json in vim?

When I label images or text for Machine Learning purposes, I often export the results in a json format. Then, I can open it in vim and simply pretty print using

:execute '%!python -m json.tool'

I often add | w which automatically writes changes to the file.

Is there a way to reverse this process? To compact the json, so there are no redundant characters?

Example input:

{
    "name": "John",
    "email": "[email protected]"
}

Desired output:

{"name":"John","email":"[email protected]"}

I would be fulfilled with Vimish, Pythonish and Bashish solution.

Upvotes: 4

Views: 2249

Answers (3)

C.R.
C.R.

Reputation: 101

You can use the same approach that you are using to format it by adding the --compact flag (requires Python 3.9+)

I have the following in my .vimrc to make it easy:

" use =j to format JSON and =J to unformat it
nmap =j :%!python -m json.tool<CR>
nmap =J :%!python -m json.tool --compact<CR>

Upvotes: 1

xenteros
xenteros

Reputation: 15842

As chepner mentioned in the comment the solution is to use:

:%!jq -c .

I have tested it and it works.

In case, one wants to save the file immediately, they can add | w to write changes.

This requires jq installed on the system which is quite a standard utility.

Upvotes: 6

Matt
Matt

Reputation: 15091

This could also be done in pure Vim:

%delete | 0put =json_encode(json_decode(@@))

But note that the field order within an object will not be preserved. So you can get

{"email":"[email protected]","name":"John"}

Upvotes: 4

Related Questions