How to encode Perl hash to JSON using JSON module?

Question

How to encode Perl hash to JSON using JSON module?

Encoding a Perl hash into JSON format is common when working with APIs or data exchange. The JSON module, included in many Perl installations (usually Perl 5.8+), allows easy serialization of Perl data structures to JSON strings.

Using the JSON Module to Encode a Hash

To encode a hash to JSON, you must pass a reference to the hash to the encoding function. The simplest way is to use encode_json which is part of JSON since Perl 5.10. Alternatively, you can create a JSON object to configure output.

Important Perl Concepts

  • Sigils and References: Hashes use the % sigil, but you almost always pass a reference (\\%) to JSON functions.
  • Context: JSON functions expect scalar context with references to maintain complex structures.
  • TMTOWTDI (There's More Than One Way To Do It): You can use either encode_json or object methods like encode.

Common Pitfalls

  • Passing a raw hash instead of a reference causes errors or data loss.
  • Beware of encoding Perl-specific data (code refs, filehandles) - they don't translate to JSON.
  • Make sure your Perl installation has the JSON module; no need to run cpan JSON inside the code.

Minimal Working Example

use strict;
use warnings;
use JSON;

# Define some data in a Perl hash
my %data = (
  name    => "Alice",
  age     => 30,
  skills  => ["Perl", "JSON", "Data"],
  active  => 1,
  details => {
    city   => "Wonderland",
    status => "active",
  },
);

# Encode hash reference to JSON string
my $json_string = encode_json(\%data);

print "Encoded JSON string:\n$json_string\n";

Output (example):

{"active":1,"age":30,"details":{"city":"Wonderland","status":"active"},"name":"Alice","skills":["Perl","JSON","Data"]}

Explanation

  • encode_json takes a reference (\\%data) and returns a JSON string.
  • The keys and values in the Perl hash become a JSON object.
  • Arrays inside the hash convert to JSON arrays.

Optional: Pretty Printed JSON

You can create a JSON object to customize encoding, e.g., pretty printing or UTF-8 output:

my $json_obj = JSON->new->utf8->pretty;

my $pretty_json = $json_obj->encode(\%data);
print "Pretty JSON output:\n$pretty_json\n";

Summary

Use the JSON module’s encode_json function with a hash reference for quick and reliable encoding of Perl hashes to JSON strings. Avoid trying to install modules inside your script, and be sure to pass references rather than raw hashes. For more control, instantiate a JSON object and call its encode method.

Verified Code

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

Tip: edit code and use “Run (Browser)”. Server runs always execute the published, verified snippet.
STDOUT
Encoded JSON string:
{"active":1,"details":{"city":"Wonderland","status":"active"},"age":30,"skills":["Perl","JSON","Data"],"name":"Alice"}
STDERR
(empty)

Was this helpful?

Related Questions