Is there a (Unix) shell script to format JSON in human-readable form?
Basically, I want it to transform the following:
{ "foo": "lorem", "bar": "ipsum" }
... into something like this:
{
"foo": "lorem",
"bar": "ipsum"
}
Is there a (Unix) shell script to format JSON in human-readable form?
Basically, I want it to transform the following:
{ "foo": "lorem", "bar": "ipsum" }
... into something like this:
{
"foo": "lorem",
"bar": "ipsum"
}
With Python 2.6+ you can just do:
or, if the JSON is in a file, you can do:
if the JSON is from an internet source such as an API, you can use
For convenience in all of these cases you can make an alias:
For even more convenience with a bit more typing to get it ready:
for all the above cases. You can put this in
.bashrc
and it will be available every time in shell. Invoke it likeprettyjson_s '{"foo": "lorem", "bar": "ipsum"}'
.UPDATE I'm using
jq
now as suggested in another answer. It's extremely powerful at filtering JSON, but, at its most basic, also an awesome way to pretty print JSON for viewing.jsonpp is a very nice command line JSON pretty printer.
From the README:
If you're on Mac OS X, you can
brew install jsonpp
. If not, you can simply copy the binary to somewhere in your$PATH
.If you use npm and Node.js, you can do
npm install -g json
and then pipe the command throughjson
. Dojson -h
to get all the options. It can also pull out specific fields and colorize the output with-i
.Simply pipe the output to
jq .
.Example:
Try
pjson
. It has colors!Install it with
pip
:⚡ pip install pjson
And then pipe any JSON content to
pjson
.That's how I do it:
It shortens the code and gets the job done.