Perl

Use of JSON with Perl

JSON is a very popular file format to work with different types of programming languages. The full form of JSON is JavaScript Object Notation which uses the syntax of the JavaScript object literal. Many modules exist in Perl to convert the JSON formatted string in Perl or the Perl data structure into the JSON format. One of them is the JSON module. You have to install this module to work with JSON data using the Perl script. The method of installing the Perl JSON module and the uses of different functions of this module to encode or decode the JSON data with the Perl script are shown in this tutorial.

Install the JSON Module

You have to install the following JSON module by executing the following command to use the JSON functions that are used in the examples of this tutorial:

$ sudo apt-get install libjson-pp-perl

Different ways of converting a JSON data into a Perl data structure or vice versa are shown in the next part of this tutorial.

Example 1: Convert a Perl Data Structure into JSON Data

The encode_json() function is used to convert any Perl data structure into a JSON data.

Syntax:

The syntax of the encode_json() function is shown in the following:

$json_data = encode_json ($perl_data);

Create a Perl file with the following script that converts the content of the hash variable into a JSON text:

#!/usr/bin/perl

#Include JSON module

use JSON;

#Declare a hash variable

my %hash_var = ('4534' => 'HDD', '8967' => 'Monitor', '9045' => 'Mouse', '7845' => 'Scanner',>#Convert the hash data into JSON data

my $json_code = encode_json \%hash_var;

my $json_length = encode_json %hash_var;

#Print the JSON data

print "The JSON code of the hash: \n$json_code\n";

print "The number of JSON properties are $json_length\n";

Output:

The following output appears after executing the script:

p1

Example 2: Convert a JSON Data into a Perl Data Structure

The decode_json() function is used to convert any JSON data into a Perl data structure.

Syntax:

The syntax of the decode_json() function is shown in the following:

$perl_data = decode_json ($json_data)

Create a Perl file with the following script that converts the content of the JSON variable into the Perl hash data:

#!/usr/bin/perl

use warnings;

use JSON;

use Data::Dumper;

#Declare a JSON variable

$json_data = '{"CSE-105":"Object Oriented Programming","CSE-206":"Advanced Java","CSE-407":"Unix Programming"

$perl_data = decode_json($json_data);

#Print the content of the dumped variable

print "The content of the decoded JSON values:\n";

print Dumper($perl_data);

Output:

The following output appears after executing the script:

p2

Example 3: Convert the Content of the JSON File into a Perl Data

Create a JSON file named “semester.json” with the following content that is used in this example:

{
    "semester": "3",
    "courses": [
        {
            "code": "CSE-105",
            "name": "Object Oriented Programming"
        },
        {
            "code": "CSE-103",
            "name": "Data structure"
        },
        {
            "code": "CSE-108",
            "name": "Algorithm"
        }
    ]
}

Create a Perl file with the following script that reads a JSON data from the “semester.json” file and convert the content of the file into the Perl data structure:

#!/usr/bin/perl

use strict;

use Data::Dumper;

use FileHandle;

use File::Basename;

use JSON;

my $filename = "semester.json";

if(my $file_handler=new FileHandle($filename)) {

  #Define the local variable to modify the listed variables while reading a file

  local $/ = undef;

  #Read the content of the JSON file

  my $json_data = <$file_handler>;

  #Close the file handler

  $file_handler->close();

  print "The content of the JSON file:\n";

  #Print the content of the JSON file

  print $json_data;

  #Decode the JSON data

  my $decoded_data = decode_json( $json_data);

  print "\nThe list of the courses of the semester-$decoded_data->{'semester'} are:\n";

  #Print the particular content of the decoded json data

  foreach my $value (@{$decoded_data->{"courses"}}) {

    print "$value->{'code'}: $value->{'name'}\n";

  }

}

else{

  #Print error message

  print "JSON File does not exist.\n";

}

Output:

The following output appears after executing the script:

p3

Example 4: Write the Perl Data into the JSON File

Create a Perl file with the following script that converts the Perl hash array into the JSON data and store the data in a JSON file named “out_file.json”:

#!/usr/bin/perl

use strict;

use warnings;

use JSON;

use Data::Dumper;

#Define the filename

my $filename = 'out_file.json';

#Define the hash variable

my %hash_data = ('id' => '88979', 'name' => 'Rakib Hossain',

    'batch' => 60, 'CGPA' => 3.67);

print "The content of the hash variable:\n";

print Dumper(\%hash_data);

#Declare the array variable that will store the content of the hash variable

my @array;

#Store the hash content in the array

push(@array, \%hash_data);

#Open the file for writing

open(OUT, ">", $filename);

#Write the content of the encoded JSON data into the file

print OUT encode_json(\@array);

close(OUT);

print "\nThe converted JSON data:\n";

#Open the file for reading

open(IN, "<", $filename) or die "File does not exits.\n";

while(<IN>)

{

  #Print each line of the file

  print $_;

}

close(IN);

#Add newline

print "\n";

Output:

The following output appears after executing the script:


p4

Conclusion

The uses of the encode_json() and decode_json() functions to covert JSON to Perl or Perl to JSON are shown in this tutorial using multiple examples.

About the author

Fahmida Yesmin

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.