Languages
[Edit]
EN

Python pretty print JSON command line

5 points
Created by:
Root-ssh
175020

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"
}

Python json pretty print entire file

cat /home/my_json_file.json | python -m json.tool

 

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join