Formatted json string in shell

20200824193301.png

Sometimes it is necessary to view json data in the terminal environment, such as when using the curl debugging interface. The directly seen json data is similar to this:

 $ echo '{"foo": "lorem", "bar": "ipsum"}' {"foo": "lorem", "bar": "ipsum"}

If you want to format and display json data in a more intuitive way, you can use the standard library json provided by python3 to achieve:

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

To make it easier to use this tool, you can set an alias for it:

Write the following to ~/.bashrc or another of your shell configuration files:

 alias pjson='python3 -m json.tool'

Execute source ~/.bashrc

Then you can use it in this shell like this:

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

references

This article is reproduced from: https://blog.frytea.com/archives/629/
This site is for inclusion only, and the copyright belongs to the original author.

Leave a Comment