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

标签 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 Debug模式,它会返回以下内容(注意,手动编辑以屏蔽敏感数据):
{
   "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.



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

最佳答案

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

(可能有一种更通用、更强大的方法来做到这一点)

关于Perl JSON 模块 |无法获得 JSON 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6044824/

相关文章:

perl - 这行 perl 在做什么?

Extjs 如何解码一个 json 字符串?

Perl - 使用重写方法避免调用 super()

Perl,从文本文件第 2 列中的每个值中减去 8

json - 将 Symfony 从 2.8 升级到 3.1 : "Your requirements could not be resolved to an installable set of packages."

javascript - 如何获取对象列表并创建列表中对象的特定属性的 JSON?

python - 在 json 中搜索键,如果该数组中不存在键,则添加默认值

java - 如何将 Retrofit 响应映射到数据模型类?

perl - 如何在 Perl 中反转句子中的单词?

php - 在自由格式文本中查找日期的最佳方法是什么?