Tuesday 27 August 2024

Pretty-Printing JSON in Shell Scripts

Working with JSON data directly in the command line can be cumbersome due to its compact and hard-to-read format. Fortunately, there are several tools and techniques you can use within a Unix shell to pretty-print JSON data, making it easier to read and debug. In this post, we’ll explore different methods to format JSON using various command-line tools.

Using jq

jq is a lightweight and flexible command-line JSON processor. It can pretty-print JSON with minimal effort:

echo '{"foo": "lorem", "bar": "ipsum"}' | jq .

This command takes a JSON string as input and pretty-prints it with proper indentations and color-coding (if your terminal supports colors).

Utilizing python -m json.tool

For those who have Python installed, the JSON module provides a simple way to pretty-print JSON:

echo '{"foo": "lorem", "bar": "ipsum"}' | python -m json.tool

This uses Python’s JSON tool to format the JSON. It’s handy because Python is pre-installed on many Unix systems.

Using json_pp

json_pp is another utility that can pretty-print JSON. It’s part of Perl’s JSON module, so it’s widely available on systems where Perl is installed:

echo '{"foo": "lorem", "bar": "ipsum"}' | json_pp

Custom Shell Function

If you frequently need to pretty-print JSON, you can define a shell function in your .bashrc or .zshrc file for easy reuse:

pretty_json() {
    echo "$1" | jq .
}

You can then call this function directly with a JSON string:

pretty_json '{"foo": "lorem", "bar": "ipsum"}'

Handling JSON Files

If you have JSON stored in a file, you can easily pretty-print it by redirecting the file content to any of these tools:

jq . somefile.json

or

python -m json.tool < somefile.json

Pretty-printing JSON in the command line improves readability and aids in debugging. Tools like jq, Python’s JSON module, and json_pp provide quick and effective ways to format JSON output. By integrating these tools into your workflow, you can handle JSON data more efficiently in shell scripts or while performing command-line operations.

Labels:

0 Comments:

Post a Comment

Note: only a member of this blog may post a comment.

<< Home