May 08, 2021 JSON
This tutorial will teach us how to encode and decode JSON objects using the Perl programming language. Let's first prepare the environment for Perl programming for JSON.
Before we can start using Perl encoding and decoding JSON, we need to install the JSON module, which can be obtained from CPAN. After downloading JSON-2.53.tar.gz or any other up-to-date version, follow these steps:
$tar xvfz JSON-2.53.tar.gz
$cd JSON-2.53
$perl Makefile.PL
$make
$make install
Function | The library |
---|---|
encode_json | Turn a given Perl data structure into a binary string encoded by UTF-8. |
decode_json | Decode the JSON string. |
to_json | Convert the given Perl data structure to a JSON string. |
from_json | Accept a JSON string and try to parse it, returning a result reference. |
convert_blessed | By passing true to this function, Perl can convert the object to JSON using the TO_JSON method of the object class. |
Perl'encode_json() function converts a given Perl data structure to a binary string encoded by UTF-8.
Grammar:
$json_text = encode_json ($perl_scalar );
or
$json_text = JSON->new->utf8->encode($perl_scalar);
Example:
The following example shows using Perl to convert an array to 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";
The results are generated on execution as follows:
{"e":5,"c":3,"a":1,"b":2,"d":4}
The following example shows how to convert a Perl object 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";
The results are generated on execution as follows:
{"birthdate":"8/5/1974 12:20:03 pm","name":"sachin","hobbies":"sports"}
Perl's decode_json() function is used to decode JSON in Perl. This function returns a value from JSON decoding to the appropriate Perl type.
Grammar:
$perl_scalar = decode_json $json_text
or
$perl_scalar = JSON->new->utf8->decode($json_text)
Example:
The following example shows how to decode jSON objects using Perl. If you don't have a Data::D on your machine then you need to install it.
#!/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);
The results are generated on execution as follows:
$VAR1 = {
'e' => 5,
'c' => 3,
'a' => 1,
'b' => 2,
'd' => 4
};