Reputation: 15842
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?
{
"name": "John",
"email": "[email protected]"
}
{"name":"John","email":"[email protected]"}
I would be fulfilled with Vimish, Pythonish and Bashish solution.
Upvotes: 4
Views: 2249
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
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
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