[英]Perl JSON module | unable to get a JSON response
我有一個腳本,我用來填充JQgrid對象。以下代碼,從CLI執行時構建看似有效的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包,它給了我以下錯誤:
輸入無效JSON:格式錯誤的JSON字符串,無論是數組,對象,數字,字符串還是原子,在/usr/lib/perl5/site_perl/5.8.8/JSON處的字符偏移量0(在“(字符串結尾)”之前) /Any.pm第571行。
我不知道接下來要去哪里。 我對代碼所做的任何其他更改都不會在返回的字符串上放置適當的括號。
將此字符串傳遞給JSON::decode
,我看到有關字符串"This is record 1"
和"This is record 2"
字面換行符的投訴。 如果將它們轉換為\\n
怎么辦?
foreach my $row ( @{$ref} ) {
$response->{rows}[$i]{id} = @$row[0];
$response->{rows}[$i]{cell} = $row;
# escape newlines in database output
s/\n/\\n/g for @{$response->{rows}[$i]{cell}};
$i++;
}
(這可能是一種更通用,更強大的方法)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.