Languages
[Edit]
EN

Python pretty print JSON command line

5 points
Created by:
Root-ssh
69370

Hi, today we would like to show you how to pretty print JSON using python from command line level.

Quick solution:

echo '{"id": 2, "name": "Tom", "age": 25}' | python -m json.tool

Practical example:

[root]# echo '{"id": 2, "name": "Tom", "age": 25}' | python -m json.tool
{
    "age": 25,
    "id": 2,
    "name": "Tom"
}

In above example we can use: python -m json.tool

We use echo command to print our JSON and we pass it to python json tool.

Python JSON pretty print and save to file

If we want to save our pretty printed JSON to file we just need to redirect output to file.

In order to do that we can use below commnad as an example:

echo '{"id": 2, "name": "Tom", "age": 25}' | python -m json.tool > pretty-json.txt

Practical example:

[root]# echo '{"id": 2, "name": "Tom", "age": 25}' | python -m json.tool > pretty-json.txt
[root]# ls -al
total 4
drwxr-xr-x.  6 root    root      91 Oct 30 13:23 .
dr-xr-xr-x. 19 root    root     255 Oct 28 17:58 ..
-rw-r--r--.  1 root    root      50 Oct 30 13:23 pretty-json.txt
[root]# cat pretty-json.txt
{
    "age": 25,
    "id": 2,
    "name": "Tom"
}

 

Native Advertising
50 000 ad impressions - 449$
🚀
Get your tech brand or product in front of software developers.
For more information contact us:
Red dot
Dirask - friendly IT community for everyone.

❤️💻 🙂

Join