I was working with some JSONs to configure a system and, for reasons, the app did not accept pretty formatted JSON, they had to be compact (or minimized).

Ruins in the forest

So, instead of having this pretty JSON in a file:

{
    "user": "L. Skywalker",
    "species": "human",
    "color": "green"
}

I had to use this ugly and barely readable JSON instead:

{"user":"L. Skywalker","species":"human","color":"green"}

The JSON I needed was way longer with a few nested objects inside, but you got the idea. The problem I had was that one of the nested objects was missing or incomplete and the program crashed on startup.

Modifying the ugly JSON by hand is tedious and error-prone so I ended up uglifying and prettifying those JSONs many times, in multiple ways. One way is to pipe the JSON to jq to get it pretty, or to jq -c to get it ugly. Just pipe everything every time and create a bunch of files.

Or use Vim.

This is my favorite way. One of its many powerful built-in features is to modify selected text with filters. And the filters can be any command, including external programs like jq.

This way:

  • to prettify a JSON: select the ugly JSON (with shift + V) and :! jq
  • to uglify a JSON: select the pretty JSON (with shift + V) and :! jq -c.

As simple as that.

These magical commands are:

  • shift + V: switches to Visual Mode linewise, to select lines of the text. See :help visual-mode for details.
  • : switches to Command Line mode, to execute commands. See :help Cmdline for details.
  • !: specifies the filter command to use. Vim feeds this command with the selected text and replaces it with the output of the filter command.
  • jq/jq -c: the commands (filters) to modify the selected text. jq prints a pretty JSON, while jq -c uglifies the JSON into a compact output.