Using jq to format JSON on the clipboard

Hacker News Top Tools

Summary

The article explains how to use jq to format JSON from the clipboard on Linux with error handling to prevent overwriting non-JSON content.

No content available
Original Article
View Cached Full Text

Cached at: 09/02/26, 02:52 PM

# Using jq to format JSON on the clipboard Source: [https://chris48s.github.io/blogmarks/posts/2021/jsontidy/](https://chris48s.github.io/blogmarks/posts/2021/jsontidy/) [Jq](https://stedolan.github.io/jq/)is a great tool\. I use it frequently, but[this recent article](https://sequoia.makes.software/parsing-json-at-the-cli-a-practical-introduction-to-jq-and-more/)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" ``` Now`jsontidy`will format whatever is on the clipboard if it can parse as JSON but leave it alone otherwise\.

Similar Articles

Killing a `Cow` made my JSON formatter 42% faster

Lobsters Hottest

The author details how removing a Copy-on-Write (Cow) data structure improved the performance of their JSON formatter, JJPWRGEM, by 42%, making it significantly faster than Prettier and Oxfmt.

Steering Zig Fmt

Lobsters Hottest

A blog post describing two tips for using `zig fmt` effectively, highlighting its 'steerable' formatting approach where trailing commas and line breaks control layout decisions, and showcasing columnar array formatting.

vercel-labs/json-render

GitHub Trending (daily)

json-render is a Generative UI framework that enables the creation of dynamic, personalized UIs from natural language prompts using predefined components for safe and predictable output across multiple platforms.