5% assure discount from here only

Tuesday, May 31, 2011

(27) How to use JSON in perl code?

Solution :

In this post i try to show how to use JSON with perl. JSON (Javascript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. JSON is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others.

In this example i had created 1 js (javascript) file named a.js, 2 .pl (perl) files (i) index.pl and (ii) json.pl.

In a.js

function checkuser(){
var a = document.getElementById('text1').value;
var b = document.getElementById('text2').value;
$('#loading').show("fast");
$.getJSON("/cgi-bin/json.pl?",{
'user': a,
'pass': b
},function (data) {
$.each(data.check, function (i, check) {
if(check[0] != 'invalid') {
$('#msg').html('');
$(check[1]).appendTo('#msg');

}else{
$('#msg').html('');
$(check[1]).appendTo('#msg');
}
$('#loading').hide("fast");
});
});
}

(i)In index.pl

#!/usr/bin/perl -w

use strict;
use warnings;

print "Content-type: text/html\n\n";

print qq~<html>
<head>
<title>JSON Example</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js" type="text/javascript"></script>
<script src="/a.js" type="text/javascript"></script>
</head>
<body>
<div align="center">
<div id="loading" style="background-color:#fff1a8;line-height:23px;display:none;width:15%"><img src="/loading.gif" class="loading_m2"> Loading... </img></div><br>
</div>
<div align="center">
<table>
<tr>
<td>UserName:</td>
<td><input type="text" id="text1" value="Lalit"></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" id="text2" value="123456"></td>
</tr>
<tr align="center">
<td><input type="button" value="Submit" onclick="checkuser();"></td>
</tr>
</table>
</div>
<div align="center" id="msg"></div>
</body>
</html>~;

and
(ii)In json.pl

#!/usr/bin/perl -w

use CGI;
use JSON;

my $cgi = CGI->new;

my $username = $cgi->param("user");
my $password = $cgi->param("pass");
my ($return, $msg) = '';

if($username eq 'Lalit' && $password eq '123456'){
($return, $msg) = ('valid', 'Welcome Lalit');
}else{
($return, $msg) = ('invalid','You are not Authorized User');
}

my $json = JSON->new->utf8->space_after->encode({'check' =>
{'rawdata' => [$return, $msg]}});
print $cgi->header(-type => "application/json", -charset => "utf-8");
print $json;

This json script is used to check that a user is a valid user or not.