DEV Community

Bhupesh Varshney 👾
Bhupesh Varshney 👾

Posted on • Originally published at bhupesh.me on

Prettifying JSON using Vim, Python & Bash

So I recently switched my editor to Vim (last month to be exact), I will probably post my experience sometime later on. If you are interested I am documenting my vim journey (or cheatsheet) here.

Let me show you how to combine the 3 most powerful tools I use in my daily workflow to achieve this. Note that this post is only for users who are on *nix environments because they probably have Bash, Python & Vim installed anyways.

So the heavy lifting is done by Python’s JSON CLI tool

$ python3 -m json.tool ugly.json
Enter fullscreen mode Exit fullscreen mode

This will print the JSON files in a nice readable format, you can also sort key using the --sort-keys argument

Ok then that’s settled we now just need to redirect the output to the same file. Let’s write a small bash function to make this portable. Open your .bashrc or .bash_functions & put this bad boy in!

pj() {
    # prettify json using python3
    if [[-z "$1"]]; then
        echo "No file path"
        exit 1
    fi
    pretty_json=$(python3 -m json.tool "$1") && echo "$pretty_json" > "$1"
}
Enter fullscreen mode Exit fullscreen mode

Cool, now you can just do pj ugly.json to do the work.

If you had like an in-editor solution, all you need to do is add this in your vimrc or init.vim

:command Pretty !pj %:p
Enter fullscreen mode Exit fullscreen mode

This will create a Vim Ex command called Pretty which invokes our external bash function. %:p gives us the full path of the file in the buffer.

That’s it, Everything is Sexy now. Invoke the :Pretty command on your current buffer & pj will do its job.

prettify-json-in-vim

Always know your tools. Master the fuck outta them!

What’s the use if I have a plugin?

Well, I love plugins too but I know this is a very simple thing to do & can be easily achieved using things I already know, so why install an external plugin?

Wait not everything is lilies and roses. This might not be very efficient for large JSON files. Let me know if the reader finds a better way to do it.

Seems interesting?, Subscribe 🚀 to read more such cool stuff or just connect with me on Twitter.

Top comments (1)

Collapse
 
yoganandam profile image
Yogananda Muthaiah

good, if this is available in as extension