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