Perl JSON模块|无法获得JSON响应

时间:2011-05-18 12:43:12

标签: perl json

我有一个脚本用于填充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字符串,既不是数组,也不是对象,   数字,字符串或原子,字符   偏移0(在“(字符串结尾)”之前)   /usr/lib/perl5/site_perl/5.8.8/JSON/Any.pm   第571行。

我不确定下一步该怎么做。我对代码所做的任何其他更改都不会在返回的字符串上放置适当的括号。

1 个答案:

答案 0 :(得分:1)

将此字符串传递到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++;
}

(这可能是一种更通用,更健壮的方法)