How to pretty print JSON with indentation in Perl?

Question

How to pretty print JSON with indentation in Perl?

To pretty print JSON in Perl with proper indentation and human-readable formatting, the most common and easiest approach is to use the JSON core module. It provides convenient methods to convert Perl data structures (hashes, arrays) into JSON strings with nicely formatted output by enabling the pretty-print flag.

Using JSON for Pretty Printing

The key method is pretty(1) which instructs the encoder to add whitespace, indentation, and newlines for clarity. You then call encode or encode_json on your Perl structure to get a nicely formatted JSON string.

This approach takes advantage of Perl's "TMTOWTDI" philosophy — “There's More Than One Way To Do It” — since there are alternative JSON modules like JSON::XS, but JSON is the most universally installed and only requires core modules depending on your Perl version.

Example: Pretty Printing JSON with Indentation

#!/usr/bin/env perl
use strict;
use warnings;
use JSON;

my $data = {
    name    => "Alice",
    age     => 30,
    hobbies => [ "Reading", "Cycling", "Hiking" ],
    address => {
        street => "123 Maple Street",
        city   => "Wonderland",
        zip    => "12345"
    }
};

# Create a JSON object configured for pretty printing
my $json = JSON->new->utf8->pretty(1);

# Encode Perl data structure to formatted JSON string
my $pretty_json = $json->encode($data);

print $pretty_json;

Explanation

  • JSON->new: Constructs a new JSON object.
  • utf8: Ensures output is encoded in UTF-8 (important if you have Unicode data).
  • pretty(1): Enables pretty printing—adds newlines, indentation, and spaces.
  • encode($data): Serializes the Perl variable into a JSON formatted string.

Running the above script will print JSON like this:

{
   "address" : {
      "city" : "Wonderland",
      "street" : "123 Maple Street",
      "zip" : "12345"
   },
   "age" : 30,
   "hobbies" : [
      "Reading",
      "Cycling",
      "Hiking"
   ],
   "name" : "Alice"
}

Important Notes and Common Gotchas

  • Module availability: The JSON module is in core from Perl 5.14 onward. For earlier versions, it can be installed from CPAN.
  • Unicode issues: Always use utf8 if you expect Unicode data to ensure correct encoding.
  • TMTOWTDI: Various other JSON modules exist (e.g., JSON::PP, JSON::XS, Cpanel::JSON::XS) which offer performance trade-offs, but the interface is very similar.
  • Context Sensitivity: encode returns a string (scalar context), while decode parses JSON back into a Perl data structure.
  • Pretty printing alternatives: You can customize indentation with indent method, e.g. $json->indent(2) for 2 spaces.

In summary, pretty printing JSON with indentation in Perl is straightforward with JSON’s pretty(1) method. It produces clean, easy-to-read output suitable for logging, debugging, or producing user-facing JSON files.

Verified Code

Executed in a sandbox to capture real output. • v5.34.1 • 18ms

Tip: edit code and use “Run (Browser)”. Server runs always execute the published, verified snippet.
STDOUT
{
   "name" : "Alice",
   "hobbies" : [
      "Reading",
      "Cycling",
      "Hiking"
   ],
   "address" : {
      "city" : "Wonderland",
      "street" : "123 Maple Street",
      "zip" : "12345"
   },
   "age" : 30
}
STDERR
(empty)

Was this helpful?

Related Questions