jq is the swiss army knife for dealing with JSON files. If you can install it use that.

However I often find myself in situations where, for whatever technical, legal, or just plain stupid reason I cannot install it.

If you find yourself in similar situation, here are a few tools that might help you.

What is JSON

Read a bit about JSON.

Input

Just a random JSON file:

examples/data/in.json

{"prereqs":{"runtime":{"requires":{"Code::Explain":"0.02","App::Ack":"0","Archive::Any":"0","Acme::MetaSyntactic":"1.012"}}},"name":"Perl-Maven","author":["Gabor Szabo"],"abstract":"Web application running the Perl Maven sites","no_index":{"directory":["t","inc"]},"generated_by":"ExtUtils::MakeMaker version 7.08, CPAN::Meta::Converter version 2.150005","meta-spec":{"url":"http://search.cpan.org/perldoc?CPAN::Meta::Spec","version":"2"}}

Expected Output

examples/data/out.json

{
   "no_index" : {
      "directory" : [
         "t",
         "inc"
      ]
   },
   "name" : "Perl-Maven",
   "author" : [
      "Gabor Szabo"
   ],
   "prereqs" : {
      "runtime" : {
         "requires" : {
            "App::Ack" : "0",
            "Acme::MetaSyntactic" : "1.012",
            "Archive::Any" : "0",
            "Code::Explain" : "0.02"
         }
      }
   },
   "meta-spec" : {
      "version" : "2",
      "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec"
   },
   "abstract" : "Web application running the Perl Maven sites",
   "generated_by" : "ExtUtils::MakeMaker version 7.08, CPAN::Meta::Converter version 2.150005"
}

How to use these?

Save the code in a file. Make the file executable:

chmod +x filename

Run the file and redirect the JSON string into its Standard Input (STDIN). If the JSON is in a file called "in.json":

./filename < in.json

If it is received from an API then:

curl http://... | ./filename

Perl 5

If you have Perl 5 installed you might use the following code:

examples/jq.pl

#!/usr/bin/env perl
use JSON qw(decode_json);
print JSON->new->ascii->pretty->encode(decode_json join '', <>);

You could also use one of the other JSON implementations in Perl and you can also read my Perl Tutorial.

Rakudo Perl 6

If you have Rakudo Perl 6 installed you might use the following code:

examples/perl6/jq.pl6

#!/usr/bin/env perl6
use JSON::Fast;
say to-json from-json($*IN.slurp), :pretty;

and then you can read more on the Perl 6 Maven site.

Python

examples/python/jq.py

#!/usr/bin/env python3
import json
import sys

print(json.dumps(json.loads(sys.stdin.read()), sort_keys=True, indent=4))

Please remember NOT to call this file json.py as that will not work.

An alternative Python one-liner suggested by Caleb Clark looks like this:

python -m json.tool in.json

curl ... | python -m json.tool

Ruby

It is less likely that you have Ruby installed, but in any case here is the example in Ruby:

examples/ruby/jq.rb

#!/usr/bin/env ruby
require 'json'

puts JSON.pretty_generate( JSON.parse( STDIN.read ) )