JSON with Perl


You'll need to install the JSON module from CPAN before you can start encoding and decoding JSON with Perl. Follow the procedures below after you've downloaded JSON-2.53.tar.gz or any other recent version.

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

JSON Functions

Function Libraries
encode_json Converts a Perl data structure to a binary text encoded in UTF-8.
decode_json This function decodes a JSON string.
to_json The specified Perl data structure is converted to a json string.
from_json Expects a json string and attempts to parse it, returning a reference as a result.
convert_blessed Utilize the true value of this function to allow Perl to use the TO JSON method on the object's class to convert an object to JSON.

Encoding JSON in Perl (encode_json)

The encode json() function in Perl turns a Perl data structure into a binary text encoded in UTF-8.


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


The following example uses Perl to display arrays under JSON.

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

This will provide the following result when executed:


The following example demonstrates how to convert Perl objects to JSON.

#!/usr/bin/perl 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; $JSON->convert_blessed(1); $e = new Emp( "sachin", "sports", "8/5/1974 12:20:03 pm"); $json = $JSON->encode($e); print "$json\n";

On executing, it will produce the following result −

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

Decoding JSON in Perl (decode_json)

The decode json() function in Perl is used to decode JSON. This function converts the value decoded from json into a Perl type.


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


The following example demonstrates how to decode JSON objects using Perl. If you don't already have it on your PC, you'll need to install the Data::Dumper module.

#!/usr/bin/perl use JSON; use Data::Dumper; $json = '{"a":1,"b":2,"c":3,"d":4,"e":5}'; $text = decode_json($json); print Dumper($text);

When you run it, you'll get the following result:

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