JSON

JSON with Perl

JSON with Perl

This section describes how to encode/decode JSON in Perl. Many modules exist in open source that can easily convert Perl data structures to JSON, and vice versa. Some popular ones are given below

  1. JSON
  2. JSON::PP
  3. JSON::Syck
  4. JSON::XS
  5. Cpanel::JSON::XS
  6. Mojo::JSON, part of Mojolicious.
  7. JSON::MaybeXS The recommended!
  8. JSON::Meth

JSON::PP is a Pure-Perl implementation that can be found in the recent releases of Perl core.  JSON::MaybeXS is a wrapper around a number of these implementations.  For JSON to work in Perl, you need to install JSON module from CPAN. Once you downloaded JSON module, say JSON-x.yy.tar.gz where x.yy refers to it version, follow the steps mentioned below to make it work.

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

The main JSON functions to work in Perl are encode_json(), decode_json(), to_json() and from_json()

  1. encode_json 🡪 this function converts the given Perl data structure to a UTF-8 encoded binary string.
  2. decode_json 🡪 this function decodes a JSON string.
  3. to_json 🡪 this function converts the given Perl data structure to a json string.
  4. from_json 🡪 this function expects a json string, parse it and returns the resulting reference.

convert_blessed 🡪 this function is used to tell Perl to use TO_JSON method on the object's class to convert an object into JSON (if convert_blessed() is set true).

encode_json() converts the given Perl data structure to a unicode binary string. Its syntax is 

$json_text = encode_json ($perl_scalar );
or
$json_text = JSON->new->utf8->encode($perl_scalar);
Let’s see this function in action.
#!/usr/bin/perl
use JSON;
my %country_code = ('India' => "IN", 'Pakistan' => "PK", 'China' => "CH", 'SriLanka' => "SL");
my $json = encode_json \%country_code;
print "$json\n";
The output of this code is 
{'India':"IN",'Pakistan':"PK",'China':"CH",'SriLanka':"SL"}

Now, time to move to decode_json() in Perl. This function decodes a JSON string in Perl returning the value decoded from json to an appropriate Perl type. See the following code to understand this function better. 

Its syntax is 

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

Time for some coding work! The below code snippet converts json string toa perl variable. 

#!/usr/bin/perl
use JSON;
use Data::Dumper;
$jsonCountrycode = '{'India':"IN", 'Pakistan':"PK", 'China':"CH", 'SriLanka': "SL"}';
$myText = decode_json ($jsonCountrycode);
print Dumper($mytext);

The output of this code will be

$VAR1 = {'India' => "IN", 'Pakistan' => "PK", 'China' => "CH", 'SriLanka' => "SL"};