Formatting JSON Output using Bash
This article explains how to format and output JSON using Bash, the Linux command-line language. It explains how to use it as what’s commonly referred to as a “beautifier”.
Command to Format JSON
The easiest way to format JSON in Bash is to use Python’s standard library. Use the following command:
python -m json.tool
Usage Example
Next, here’s a specific usage example. Running the following command will output formatted JSON data.
ruby ~/pg/ruby/dev.rb | restrictstdout | python -m json.tool | ascii2uni -a U -q
In the above command, the JSON data generated by ruby ~/pg/ruby/dev.rb is limited by restrictstdout, formatted by python -m json.tool, and finally converted to Unicode by ascii2uni -a U -q.
Here’s an example output:
[
{
"title": "logical jekyll"
},
{
"categories": "note",
"content": "`sudo apt update && sudo apt install nodejs npm -y`",
"date": "2019-01-17 07:41:09 +0900",
"post": "---\nlayout: post\ntitle: \"node.js npm をubuntu 18.04にインストール\"\ndate: 2019-01-17 07:41:09 +0900\ncategories: note\n---\n\n`sudo apt update && sudo apt install nodejs npm -y`\n",
"title": "node.js npm をubuntu 18.04にインストール"
}
]
This way, the formatted JSON data is output in an easy-to-read format.
Summary
When formatting and outputting JSON in Bash, using Python’s json.tool module is convenient. With this method, you can easily format and check even complex JSON data.