DEV Community

loading...

jq hack #1: colored less

sshine profile image Simon Shine ・1 min read

Sometimes you want to look at a lot of JSON output in the terminal. Sometimes this JSON output is nicely formatted, and often it is compacted by a REST endpoint. Examples of verbose output:

$ kubectl get nodes -o json
$ curl 'https://hacker-news.firebaseio.com/v0/topstories.json'
Enter fullscreen mode Exit fullscreen mode

In both cases you can pipe the output through:

$ ... | jq -C . | less -R
Enter fullscreen mode Exit fullscreen mode

The -C parameter to jq forces colors. When omitted, jq will only print colors when an interactive terminal is detected. Piping further into less removes the colors. Additionally, we have to tell less to interpolate those ANSI colors so that we don't see a bunch of ESC[1;39m codes.

$ kubectl get nodes -o json | jq -C . | less -R
{
  "apiVersion": "v1",
  "items": [
    {
      "apiVersion": "v1",
      "kind": "Node",
      "metadata": {
        "annotations": {
...
:
Enter fullscreen mode Exit fullscreen mode

Discussion (2)

Collapse
aakatev profile image
Artem

Great tip. I imagine it can also be used with other CLI tools dumping ANSI color codes.

Collapse
sshine profile image
Simon Shine Author

Yes, definitely! This was inspired by another trick I did with ack some years ago:

What if, when you grep, it goes into pager mode when results don't fit one screen?

It means that the UNIX programs are designed well, in my opinion. :-)

Forem Open with the Forem app