Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print colored raw output with jq on terminal

I'm trying to print a report on the terminal. The report is JSON and I print it on the terminal as a raw jq output.

I'm trying to color the output for few values something on the lines of

echo -e "\033[31m Hello World"

but have been unable to do so.

When I do something like below

echo '[{"value": "New", "onclick": "Ready"},{"value": "Old", "onclick": "Stopped"}]' | jq -r  '.[] | "\n", .value, .onclick '

It prints

New

Ready

Old

Stopped

So it understands \n new line character but I want to have something like this

New (In Bold and Red Color)

Ready

Old (In Bold and Red Color)

Stopped

to make it more readable

like image 913
ankitj Avatar asked Sep 12 '25 20:09

ankitj


1 Answers

This illustration should be enough to get you over the hurdle:

jq -n -r '

def colors:
 {
 "black": "\u001b[30m",
 "red": "\u001b[31m",
 "green": "\u001b[32m",
 "yellow": "\u001b[33m",
 "blue": "\u001b[34m",
 "magenta": "\u001b[35m",
 "cyan": "\u001b[36m",
 "white": "\u001b[37m",
 "reset": "\u001b[0m",
};

colors.red + "red" + colors.green + "green"
'

Elaboration

# print $text in the specified color
def pc($text; color):
  (colors | color) + $text + colors.reset;

# Usage example:
pc("red"; .red) + pc("green"; .green)
like image 110
peak Avatar answered Sep 14 '25 13:09

peak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!