JSON  With Perl


This chapter covers the way to encode and decode JSON objects using the Perl programming language. Let's start with preparing the environment to begin our programming with Perl for JSON.


Before you begin encoding and decoding JSON using Perl, you want to install a JSON module, which may be obtained from CPAN. Once you downloaded JSON-2.53.tar.gz or some other latest version, follow the steps noted below −

$tar xvfz JSON-2.53.tar.gz
$cd JSON-2.53
$perl Makefile.PL
$make install

JSON Functions




Converts the given Perl data structure to a UTF-8 encoded, binary string.


Decodes a JSON string.


Converts the given Perl data structure to a json string.


Expects a json string and tries to parse it, returning the resulting reference.


Use this function with true value so that Perl can use the TO_JSON method on the object's class to convert an object into JSON.

Encoding JSON in Perl (encode_json)

The Perl encode_json() function transforms the available Perl data structure to a UTF-8 encoded, binary string.


$json_text = encode_json ($perl_scalar );
$json_text = JSON->new->utf8->encode($perl_scalar);


Arrays under JSON with Perl is shown in the below given example:

use JSON;
my %rec_hash = ('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
my $json = encode_json \%rec_hash;
print "$json\n";

While applying, you will generate the result given below:
How Perl objects can be transformed into JSON, in the below given example:
package Emp;
sub new {
   my $class = shift;
   my $self = {
      name => shift,
      hobbies  => shift,
      birthdate  => shift,
   bless $self, $class;
   return $self;

sub TO_JSON { return { %{ shift() } }; }
package main;
use JSON;

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

$e = new Emp( "sachin", "sports", "8/5/1974 12:20:03 pm");
$json = $JSON->encode($e);
print "$json\n";

After applying, it will generate the below given result:

{"birthdate":"8/5/1974 12:20:03 pm","name":"sachin","hobbies":"sports"}

Decoding JSON in Perl (decode_json)

The Perl decode_json() function is made in use for decoding JSON in Perl. This function gives back the value decoded from JSON to an appropriate Perl type.


$perl_scalar = decode_json $json_text
$perl_scalar = JSON->new->utf8->decode($json_text)


The below given example represents how Perl can be made in use to decode JSON objects. Here you want to install the Data::Dumper module if you already do not have it on your device.

use JSON;
use Data::Dumper;

$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';

$text = decode_json($json);
print  Dumper($text);

On applying, it will generate result given below:

$VAR1 = {
   'e' => 5,
   'c' => 3,
   'a' => 1,
   'b' => 2,
   'd' => 4