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"
}
command-lineformatjsonpretty-printunix
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"
}
Best Solution
With Python 2.6+ you can 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"}'
.Note that as @pnd pointed out in the comments below, in Python 3.5+ the JSON object is no longer sorted by default. To sort, add the
--sort-keys
flag to the end. I.e.... | python -m json.tool --sort-keys
.