Go4Expert

Go4Expert (http://www.go4expert.com/)
-   Perl (http://www.go4expert.com/articles/perl-tutorials/)
-   -   Introduction to JSON in Perl (http://www.go4expert.com/articles/introduction-json-perl-t27215/)

pradeep 25Nov2011 15:44

Introduction to JSON in Perl
 
JSON has become a popular data representation format, and can been seen as the successor of XML which used to be the most popular format used for data exchange between systems. Notable examples of JSON being used for data representation are Facebook Graph API & Flickr API, amongst many others. Javascript frameworks like jQuery & and the likes have in-built support for automatic handling of JSON responses in AJAX calls.

JSON Parsing in Perl



Like most of the Perl modules JSON module is found on CPAN, which under the hood has a C API (JSON::XS) as well as Pure-Perl API (JSON:PP) which is used in case the C-API is unavailable, the C API being faster of the two.

Now let's see an example:

Open http://graph.facebook.com/pradeep.deepz in your web browser and you'll get the following content.

Code:

{
  "id": "703880701",
  "name": "Pradeep Deepz",
  "first_name": "Pradeep",
  "last_name": "Deepz",
  "link": "http://www.facebook.com/pradeep.deepz",
  "username": "pradeep.deepz",
  "gender": "male",
  "locale": "en_IN"
}

Here is the code to parse the JSON and print name & locale.

Code: Perl

use strict;
use warnings;
use LWP::Simple;
use JSON;

my $json_data = get(q[http://graph.facebook.com/pradeep.deepz]);
my $json_obj = new JSON;
my $perl_data = $json_obj->decode($json_data);

printf('Name: %s & locale: %s',$perl_data->{name},$perl_data->{locale})


Output:
Code:

Name: Pradeep Deepz & locale: en_IN

JSON generation in Perl



Like we parse JSON we may also output data in JSON format, like example for AJAX calls, for data exchange with other systems, etc.

Code: Perl

use strict;
use warnings;
use JSON;

my $json_obj = new JSON;

## Build some Perl data
my %perl_data;
my @friends1 = qw[Shabbir Anjan Sajal Navin];
my @friends2 = qw[Sanket Taneesha Sreekutty];

$perl_data{Pradeep} = { locale => 'en_IN', friends => \@friends1 };
$perl_data{Anjali} = { locale => 'en_IN', friends => \@friends2 };

print $json_obj->pretty->encode(\%perl_data);


Output:
Code:

{
  "Pradeep" : {
      "friends" : [
        "Shabbir",
        "Anjan",
        "Sajal",
        "Navin"
      ],
      "locale" : "en_IN"
  },
  "Anjali" : {
      "friends" : [
        "Sanket",
        "Taneesha",
        "Sreekutty"
      ],
      "locale" : "en_IN"
  }
}

Hopefully, this will help people start off with handling JSON in their Perl scripts, next time I will write about the advanced features of the JSON module and how they will be of help.


All times are GMT +5.5. The time now is 13:40.