Skip to content
Tech News
← Back to articles

Using jq to format JSON on the clipboard

read original more articles
Why This Matters

This article highlights how developers can streamline JSON formatting directly from the clipboard using jq and simple command-line aliases, enhancing productivity and reducing manual formatting steps. It also emphasizes the importance of error handling to prevent unintended clipboard overwrites, making these tools more reliable for everyday use.

Key Takeaways

Jq is a great tool. I use it frequently, but this recent article from Sequoia McDowell still has some great tips in it. Well worth a read. One thing that stood out to me from this post was the snippet:

I like this pretty-printing/formatting capability so much, I have an alias that formats JSON I've copied (in my OS "clipboard") & puts it back in my clipboard: alias jsontidy="pbpaste | jq '.' | pbcopy"

That's crazy-useful, but I need to tweak it a bit. Firstly, as noted, pbcopy and pbpaste are mac utils. No worries. We can substitute xclip on Linux:

xclip -selection clipboard -o | jq '.' | xclip -selection clipboard

I spotted a minor problem here though: If I run this and the text on my clipboard isn't JSON then jq will exit with a non-zero code, output something like parse error: Invalid numeric literal at line 1, column 6 to stderr and nothing to stdout. Pipe doesn't care about the non-zero exit code though so we overwrite whatever was on the clipboard with an empty string. So lets add a bit of error handing:

alias jsontidy = "xclip -selection clipboard -o | (jq '.' || xclip -selection clipboard -o) | xclip -selection clipboard"