Sunday, March 29, 2015

JSON in PERL explained with example

Using JSON with PERL :


Dealing with JSON in Perl is more complex comparing to other as Perl being a type less language. However, JSON can be either encoded or decoded using PERL for this operation, JSON module must be installed first.JSON-2.53.tar.gz searching it would let you get a module for PERL of JSON. You will find JSON functions to operate with JSON data using PERL.

JSON Function:

Encode_json : It converts PERL structure which is given in to a UTF-8 encoded, binary string.
syntax:
$json_text = encode_json ($perl_scalar );
or
$json_text = JSON->new->utf8->encode($perl_scalar);


Example for encoding JSON in PERL:

Perl File (encode.pl)
#!/perl/bin/perl  
 print "Example of encode\n";  
 use JSON;  
 my %rec_hash = ('PHP' => 1, 'SEO' => 2, 'JS' => 3, 'JSON' => 4, 'Project' => 5);  
 my $json = encode_json \%rec_hash;  
 print "$json\n";  
 Decode_json : It decodes the JSON string.  
 syntax:  
 $perl_scalar=decode_json $json_text  
 or  
 $perl_scalar= JSON->new->utf8->decode($json_text)  

Example for decoding JSON in PERL:

Perl File (decode.pl)
 #!/perl/bin/perl  
 print "Example of decode\n";  
 use JSON;  
 use Data::Dumper;  
 $json = '{"JSON":1,"JavaScript":2,"SEO":3,"HTML":4,"CSS":5}';  
 $content = decode_json($json);  
 print Dumper($content); 



No comments:

Post a Comment