DebugPointer
Published on

Pretty Print or Format JSON in a shell

Pretty Print or Format JSON in a shell

Install jq. It is a very simple and handy tool to pretty print JSON in a formatted manner.

For linux users-

$ sudo apt-get update
$ sudo apt-get install jq

For MAC users-

$ brew install jq

Pretty Print JSON string in Shell

In your shell, you can echo a JSON string and pipe (|) it with jq and you'll see a pretty JSON output.

$ echo '{ "name": "Gary", "email": "hello@example.com"}' | jq

Output will look like-

{
  "name": "Gary",
  "email": "hello@example.com"
}

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 shell

$ 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 shell

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 shell.

$ jq

jq can be used on JSON string, files, stream, and more.

Learn more about jq in the official jq tutorial