Following are the encode and decode processes for JSON by Perl.
The functionality of
encode_json
function is to data structure of Perl to a UTF-8 format and binary string also. Following is the syntax for encode_json .
$json_text = encode_json ($perl_scalar );
or
$json_text = JSON->new->utf8->encode($perl_scalar);
The following is an example of data structure for Perl.
[html]
my $student = {
name => 'Foo Bar',
email => 'foo@bar.com',
gender => undef,
classes => [
'Chemistry',
'Math',
'Literature',
],
address => {
city => 'Fooville',
planet => 'Earth',
},
};
[/html]
Now use encode_json function to the data structure into JSON string as follows.
json_encode.pl
[html]
use strict;
use warnings;
use 5.010;
use qw(encode_json decode_json);
my $student = {
name => 'Foo Bar',
email => 'foo@bar.com',
gender => undef,
classes => [
'Chemistry',
'Math',
'Litreture',
],
address => {
city => 'Fooville',
planet => 'Earth',
},
};
my $student_json = encode_json $student;
say $student_json;
[/html]
Where
Cpanel::JSON::XS
module changes over Perl information structures to JSON and the other way around. It's essential objective is to be right and its auxiliary objective is to be quick.
CPAN
is the Comprehensive Perl Archive Network, an expansive accumulation of Perl programming and documentation.
CPAN module knows how to handle Unicode with Perl adaptation higher than 5.8.5, archives how and when it does as such. CPAN module has both a functional interface and object-oriented interface. Following is the image description for the code.
Output: Now compile the code result will be as follows.
[html]
{"classes":["Chemistry","Math","Literature"],"gender":null,"name":"Foo Bar","email":"foo@bar.com","address":{"city":"Fooville","planet":"Earth"}}
[/html]
The functionality of
decode_json
function is to give back value from JSON by performing decode to Perl.
Following is the syntax for decode_json .
$perl_scalar = decode_json $json_text
or
$perl_scalar = JSON->new->utf8->decode($json_text)
Following is an example.
json_decode.pl
[html]
use strict;
use warnings;
use 5.010;
use Cpanel::JSON::XS qw(encode_json decode_json);
my $student_json = '{"classes":["Chemistry","Math","Litreture"],"gender":null,"name":"Foo Bar","email":"foo@bar.com","address":{"city":"Fooville","planet":"Earth"}}';
my $student = decode_json $student_json;
use Data::Dumper;
print Dumper $student;
[/html]
Output: Now compile the code result will be as follows.
[html]$VAR1 = {
'gender' => undef,
'email' => 'foo@bar.com',
'address' => {
'planet' => 'Earth',
'city' => 'Fooville'
},
'classes' => [
'Chemistry',
'Math',
'Literature'
],
'name' => 'Foo Bar'
};
[/html]