If you’re like me, dealing with JSON data can sometimes feel like walking through a maze with all its nested arrays and objects. We all know how important it is to handle JSON data correctly, especially when it comes to scripting in bash. And that’s why I’m here today to share a secret weapon of mine – ‘jq’. It’s a powerful tool that makes JSON a piece of cake. So, let’s dive right into our topic, Pretty Printing JSON in bash using jq.
Install jq
. It is a very simple and handy tool to pretty print JSON in a formatted manner. jq
is a command-line utility for working with JSON data. JSON (JavaScript Object Notation) is a lightweight data interchange format that is widely used to exchange data between web applications and servers. jq
allows you to manipulate, filter, and extract data from JSON files, making it a powerful tool for working with JSON data.
Installation of jq
For linux users-
$ sudo apt-get update
$ sudo apt-get install jq
For MAC users-
$ brew install jq
Pretty Print JSON in Bash using jq
In your bash, you can echo
a JSON string and pipe (|
) it with jq
and you’ll see a pretty JSON output.
$ echo '{ "name": "Gary", "email": "[email protected]"}' | jq
Output will look like-
{
"name": "Gary",
"email": "[email protected]"
}
jq
can handle large JSON structures without any performance issues. It has been a great tool that I’ve used over the years.
Pretty Print JSON file in bash using jq
$ jq --color-output . file1.json file1.json | less -R
Any command that would generate a JSON output, it can be piped to print a formatted JSON-
$ command_with_json_output | jq .
Pretty Print API response in bash using jq
An example from the docs, where you can pretty print a API response which is JSON-
$ curl 'https://api.github.com/repos/stedolan/jq/commits?per_page=5' | jq '.'
You can also play around in the interactive mode of jq
, by just entering jq
in the bash.
$ jq
jq
can be used on JSON string, files, stream, and more.
Learn more about jq
in the official jq tutorial
Using jq
is one of the easiest and most convenient way to pretty print a JSON in a bash script.
As we wrap up our journey, I hope you’re now feeling more confident and less daunted when dealing with JSON in bash. With ‘jq’, we have unlocked a more user-friendly way to handle JSON data. Remember, it’s all about making things easier and more efficient for ourselves. So, keep exploring, keep learning, and remember, there’s always a tool like ‘jq’ to simplify the complex. Until next time, happy scripting!