我有我使用的填充jqGrid的object.The下面的代碼,當從CLI執行的建立似乎是一個有效的JSON查詢腳本Perl JSON模塊|無法獲得JSON響應
#!/usr/bin/perl
use CGI;
use DBI;
use JSON;
use Test::JSON;
use POSIX qw(ceil);
use strict;
use warnings;
my $cgi = CGI->new;
my $page = $cgi->param('page');
my $limit = $cgi->param('limit');
my $sidx = $cgi->param('sidx');
my $sordx = $cgi->param('sordx');
if(!$sidx) {$sidx = 1};
my $start = $limit*$page - $limit;
my $dbh = DBI->connect('dbi:mysql:hostname=localhost;database=test',"test","test") or die $DBI::errstr;
my $count = $dbh->selectrow_array("SELECT COUNT(id) AS count FROM test;");
my $sql = "SELECT ID, Name FROM test ORDER BY ? ? LIMIT ?, ?;";
my $sth = $dbh->prepare($sql) or die $dbh->errstr;
$sth->execute($sidx,$sordx,$start,$limit) or die $sth->errstr;
my $total_pages;
if($count >0) {
$total_pages = ceil($count/$limit);
} else {
$total_pages = 0;
}
if ($page > $total_pages){ $page=$total_pages};
$start = $limit*$page - $limit;
my $i=0;
my $response = {};
$response->{page} = $page;
$response->{total} = $total_pages;
$response->{records} = $count;
while (my $row = $sth->fetchrow_arrayref) {
my @arr = @{$row};
$response->{rows}[$i]{id} = $row->[0];
$response->{rows}[$i]{cell} = \@arr;
$i++;
}
Test::JSON::is_valid_json $response, '... json is well formed';
print $cgi->header(-type => "application/json", -charset => "utf-8");
print JSON::to_json($response,{ ascii => 1, pretty => 1 });
如果我把劇本到CGI調試模式下,它返回下面的(注意,手動編輯掩蓋敏感數據):
{
"page" : "1",
"records" : "35",
"rows" : [
{
"id" : "15675",
"cell" : [
"15675",
"Test 1"
]
},
{
"id" : "15676",
"cell" : [
"15676",
"Test 2"
]
}
],
"total" : 4
}
編輯:我添加的Test :: JSON包,它給了我下面的錯誤:
input was not valid JSON: malformed JSON string, neither array, object, number, string or atom, at character offset 0 (before "(end of string)") at /usr/lib/perl5/site_perl/5.8.8/JSON/Any.pm line 571.
我不知道下一步該去哪裏。對代碼進行的任何其他更改都不會在返回的字符串上放置適當的括號。
簡化程序,以幫助調試。編碼此文字數據結構是否按預期工作? 'print JSON :: to_json({page => undef,records => 25,rows => [{cell => [1,「1999-01-01」,(「0.00」)x 3,「帶標點符號的註釋」 ],id => 1},{cell => [2,「2001-01-10」,103.98,45.34,149.32,「This is record 1」],id => 2},{cell => [3, 「2001-02-10」,104.98,46.34,151.32,「這是記錄2」],id => 3}],total => 0})' – daxim 2011-05-18 19:48:20
嗯,當然'Test :: JSON :: is_valid_json $響應「告訴你它不是有效的JSON。那時,'$ response'就是hashref_before_它被編碼成JSON。 – cjm 2011-05-19 05:36:09