DEV Community

Simon Shine
Simon Shine

Posted on β€’ Edited on

1 2

jq hack #1: colored less

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

Here,

  • jq -C:

    --color-output / -C and --monochrome-output / -M:
    
    By default, jq outputs colored JSON if writing to a terminal.
    You can force it to produce color even if writing to a pipe
    or a file using -C, and disable color with -M.
    
  • less -R:

    -R or --RAW-CONTROL-CHARS
    
    Like -r, but only ANSI "color" escape sequences are output in
    "raw" form. Unlike -r, the screen appearance is maintained
    correctly in most cases. ANSI "color" escape sequences are
    sequences of the form:
    
        ESC [ ... m
    
    where the "..." is zero or more color specification characters.
    For the purpose of keeping track of screen appearance, ANSI color
    escape sequences are assumed to not move the cursor. [...]
    

API Trace View

Struggling with slow API calls? πŸ•’

Dan Mindru walks through how he used Sentry's new Trace View feature to shave off 22.3 seconds from an API call.

Get a practical walkthrough of how to identify bottlenecks, split tasks into multiple parallel tasks, identify slow AI model calls, and more.

Read more β†’

Top comments (2)

Collapse
 
secure_daily 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 β€’

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. :-)

Sentry image

See why 4M developers consider Sentry, β€œnot bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay