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"
}
You can use:
jq
It's very simple to use and it works great! It can handle very large JSON structures, including streams. You can find their tutorials here.
Here is an example:
Or in other words:
It is not too simple with a native way with the jq tools.
For example:
With Perl, if you install JSON::PP from CPAN you'll get the json_pp command. Stealing the example from B Bycroft you get:
It's worth mentioning that
json_pp
comes pre-installed with Ubuntu 12.04 (at least) and Debian in/usr/bin/json_pp
I recommend using the json_xs command line utility which is included in the JSON::XS perl module. JSON::XS is a Perl module for serializing/deserializing JSON, on a Debian or Ubuntu machine you can install it like this:
It is obviously also available on CPAN.
To use it to format JSON obtained from a URL you can use curl or wget like this:
or this:
and to format JSON contained in a file you can do this:
To reformat as YAML, which some people consider to be more humanly-readable than JSON:
With Perl, use the CPAN module
JSON::XS
. It installs a command line tooljson_xs
.Validate:
Prettify the JSON file
src.json
topretty.json
:If you don't have
json_xs
, tryjson_pp
. "pp" is for "pure perl" – the tool is implemented in Perl only, without a binding to an external C library (which is what XS stands for, Perl's "Extension System").Install yajl-tools with the command below:
sudo apt-get install yajl-tools
then,
echo '{"foo": "lorem", "bar": "ipsum"}' | json_reformat