Perl解析json数据

 filename: json_test.pl

解析json格式数据 1.解析curl返回的json数据;2.解析文件中的json串。

测试用文件json_result.txt的内容见本段代码后;

#!/usr/bin/perl -w

use WWW::Curl::Easy;
use JSON;
use Data::Dumper;

my $json = new JSON;
my $curl = new WWW::Curl::Easy;

my $response_body="";
my $retcode=1;

$curl->setopt(CURLOPT_URL,'192.168.0.20/GetAgent?eId=3000&cno=2000');
$curl->setopt(CURLOPT_WRITEDATA,\$response_body);

$retcode = $curl->perform;
print $retcode."\n";

my $obj = $json->decode($response_body);

#print Dumper($obj);

my $dial_interface = $obj->{'dial_interface'};
my $dial_cno = $obj->{'dial_cno'};
my $dial_tel = $obj->{'dial_tel'};
my $agent_login_status = $obj->{'agent_login_status'};
my $agent_device_status = $obj->{'agent_device_status'};

print $dial_interface."\n";
print $dial_cno."\n";
print $dial_tel."\n";
print $agent_login_status."\n";
print $agent_device_status."\n";
#-------------------------------
open(JFILE,"</home/perl/json_result.txt");
while(<JFILE>) {
    print $_;
    my $item_line = $json->decode($_);
    my $dial_interface = $item_line->{'interface'};
    my $dial_cno = $item_line->{'cno'};
    my $dial_tel = $item_line->{'tel'};
    my $agent_login_status = $item_line->{'agent_login_status'};
    my $agent_device_status = $item_line->{'agent_device_status'};
    print $interface."\n";
    print $cno."\n";
    print $tel."\n";
    print $agent_login_status."\n";
    print $agent_device_status."\n";
}
close(JFILE);
json_result.txt里的内容
{"interface":"7777@32000","cno":"2000","tel":"7777","agent_login_status":"online","agent_device_status":"idle"}
{"interface":"6666@2001","cno":"2001","tel":"6666","agent_device_status":"idle"}
运行json_test.pl的输出结果如下:

0 7777@2000 2000 7777 online idle {"interface":"7777@2000","agent_device_status":"idle"} 7777@2000 2000 7777 online idle {"interface":"6666@2001","agent_device_status":"idle"} 6666@32001 2001 01041006666 online idle

相关文章

1. 如何去重 #!/usr/bin/perl use strict; my %hash; while(...
最近写了一个perl脚本,实现的功能是将表格中其中两列的数据...
表的数据字典格式如下:如果手动写MySQL建表语句,确认麻烦,...
巡检类工作经常会出具日报,最近在原有日报的基础上又新增了...
在实际生产环境中,常常需要从后台日志中截取报文,报文的形...
最近写的一个perl程序,通过关键词匹配统计其出现的频率,让...